Pages

Thursday, January 19, 2012

Sql Server - "Handy" While loop

I came across a situation today... I wrote a sql script that finds the last record inserted by each user for each day within a given date range. The script was bit tricky, but I managed it. To test it, however, I have to have enough data inserted to the table, and of course delete them when I am done. I could write a console application that could do it. That means new project, sql connection/command, random data generation.  But, something quick and in sql would be nice. You know what I mean !!

While researching I came across "while" loop in Sql Server, and below is how I got the test data generated.

While loop is pretty straight forward in sql:
while <condition>
   begin
   ......
   end

For example:
declare @i int
set @i = 1
while @i<10
  begin
      print @i
      set @i = @i + 1
  end

The output would be: 1 2 3 4 5 6 7 8 9 (each number in new line)

In my case, it would be something like below. I am using a test table, 'myTestTable' which has 4 columns: pk, note, createDate, and userId.
declare @c datetime
set @c = getdate()
while @c > dateadd(dd, -10, getdate())
begin
print @c
insert into myTestTable
values ('my test data', @c, 'chhetri')
set @c = dateadd(day, -1, @c)
end

Neat. This inserted 9 records in my table with different date stamp. If I need more data, say 24 records per day, then while resetting @c inside the loop, I could do:
set @c=dateadd(hour, -1, @c)

Deleting my test data is also simple. I would just look for records that has 'chhetri' in the userId column.

Again, not the only solution. How would you solve it?

No comments:

Post a Comment