Archive for the ‘SQL Server’ Category

Rollover logging in database

June 3, 2008

We are currently working on an application (window service), which grabs alerts data from a third party web application and parses each alert and process its status, reasons, and source for different attributes and then creates tickets for support staff.

In this project we were logging all detail activities of parsing alerts into our database, which alert was raised, what was the source and ip address and so on. Our service was grabbing data from that website after five minutes interval. There were nearly hundreds of alerts on each pass. So our log table was getting heavy each day.

We decided to implement rollover logging into this, so that previous logs could be discarded if not required. So we came up with following solution. In it we move yesterday’s log entries to a new table, and truncated current log table.

ALTER PROCEDURE [dbo].[LogEntry]
(
    @AlertID AS int,
    @Message AS varchar(1000)
)
AS

DECLARE @TableName AS nvarchar(200),
        @CurrentDate AS datetime,
        @PreviousDate AS datetime

SELECT
    @PreviousDate = getdate()-1,
    @CurrentDate = getdate()

SELECT
    @TableName = 'Logs_' + CONVERT(varchar, @PreviousDate, 112)

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@TableName) AND type IN (N'U' ) )
BEGIN
    EXEC ( 'SELECT * INTO ' + @TableName + ' FROM Logs' )
    TRUNCATE TABLE Logs
END 

INSERT INTO Logs
(
    AlertID,
    [Message],
    EntryDate
)
VALUES
(
    @AlertID,
    @Message,
    GETDATE()
)

Using boolean algebra in sql

May 16, 2008

Recently I was working on a procedure which required that I marked some items in different categories, and then based on that marking we have to summarize items in different sections. I have extracted the main idea from this procedure for our example. It is using some boolean algebra to segregate items into different sections.

(more…)

Bucketing consecutive numbers in a range

May 12, 2008

Recently we had a little tricky problem to solve. We were displaying a report in which we had to bucket numbers in a range, such that only consecutive numbers should be in that range, if any break is there, then a new range should start. Our first solution did not worked as required. Most difficult part was identifying numbers in a sequence, and placing them in a bucket. We could not create any simple T-SQL queries which could easily sort these things out. Then we thought of first capturing the bucket of each number so that we can easily work it out, and that was not possible without cursors. Lets have a look how we did that.

(more…)

T-SQL Puzzle

May 12, 2008

Recently I saw a puzzle on SQL Server Central, I was intrigued to solve it myself, so here is what I was able to accomplish, and in less than 10 minutes.

DECLARE @i int

SET @i = 0

CREATE TABLE #X
(
val int
)

WHILE @i  < 100
BEGIN

SELECT @i = @i + 1
INSERT INTO #X VALUES (@i)

END

SELECT
val,
val % 3,
val % 5,
CASE
WHEN val % 3 = 0 AND val % 5 = 0 THEN 'BIZZBUZZ'
WHEN val % 3 = 0 THEN 'BIZZ'
WHEN val % 5 = 0 THEN 'BUZZ'
END xval
FROM
#X

DROP TABLE #X

Generate random number for each row

February 16, 2007

Today I had to add a new date column to one of my table, and populate it with some random entries. I found a script from SQL Team Blog about generating random numbers. I modified it a little and used it to populate these dates based on another date I had in my table.

(more…)

Sequential Numbering/Counting of Records with SQL Server

February 9, 2007

Now say your table does not have an identify column, you don’t want to use a temporary table or alter your existing table, but you still would like to have a record number associated with each record. In this case you could use a self join to return a record number for each row. Here is an example that calculates a RecNum column, and displays the LastName for each record in the Northwind.dbo.Employees table. This example uses count(*) to count the number of records that are greater than or equal LastName in this self join.

(more…)

SCOPE_IDENTITY() and @@IDENTITY Demystified

February 9, 2007

I’ve run across several applications where the use of IDENTITY values has caused some confusion, specifically in how the @@IDENTITY function operates given external influences. We’ve all likely been faced with how to grab the newly generated IDENTITY value from a SQL Server database table. And there are a 2 popular techniques that accomplish this with SQL Server:

1. the @@IDENTITY function
2. the SCOPE_IDENTITY() function

(more…)

Converting string to datetime

February 9, 2007

Here how you can convert string date to a datetime value

DECLARE @DateString char(14)
SET @DateString = '20060703074815'   -- '20050812204332'
SELECT CAST(SUBSTRING(@DateString, 1, 4) + '-' +
SUBSTRING(@DateString, 5, 2) + '-' +
SUBSTRING(@DateString, 7, 2) + 'T' +
SUBSTRING(@DateString, 9, 2) + ':' +
SUBSTRING(@DateString, 11, 2) + ':' +
SUBSTRING(@DateString, 13, 2) AS datetime)

Get rowcount for each table

February 9, 2007

If you want to find row count for each table in your database without naming any table then use following script:

exec sp_MSforeachtable 'select count(*) as nr_of_rows, ''?'' as table_name from ?'

How to find where a table is referenced?

February 9, 2007

When you need to find all procedures and function referencing a particular table then use following

SELECT o.name, t.TABLE_NAME, c.text
FROM syscomments c JOIN sysobjects o ON c.id = o.id JOIN INFORMATION_SCHEMA.Tables t ON c.text LIKE '%'+t.TABLE_NAME+'%'