Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

21 December 2010

Reseed a table in SQL Server

In Microsoft SQL Server, it is possible to reseed an identity column of a table. If you want to start an identity column at a different value (for instance, after clearing it), you can use the following syntax:
DBCC CHECKIDENT (myTable, reseed, 0)
The next row that is added to the table will have 1 in its identity column. If we would use
DBCC CHECKIDENT (myTable, reseed, 41)
the next row would get 42 in its identity column.

Be careful when using this on tables with rows in them, if the new seed is lower than the highest currently in the table, you will encounter problems before long. When the new seed is already in use, you will get a unique key restriction violation on insert!

16 December 2010

Getting the ISO weeknumber in SQL Server 2005 (and earlier)

I just discovered that SQL Server often returns the wrong week number when using DatePart(wk, @date).
For instance, SELECT DatePart(wk, '2010-12-17') returns 47 while it should be 46.
This is because SQL Server starts counting weeks from 1 Jan, so 1 Jan is always in week 1 of the year.
The ISO standard states that week 1 is the first week with 4 days in it.
The following code can be used (with @date being the datetime) to return the ISO week

CREATE FUNCTION GetISOWeek(@date DateTime)
RETURNS INTEGER
AS
BEGIN

  declare @ISOweek INTEGER;
  select @ISOweek = datepart(wk ,@date) + 1 - 

    datepart(wk, 'Jan 4,' CAST(datepart(yy, @date) as CHAR(4)));
  if (@ISOweek = 0)
    select @ISOweek = datepart(wk, 'Dec ' + CAST(24 + 

      datepart(day, @date) AS CHAR(2)) + ','
      CAST(datepart(yy, @date) - 1 as CHAR(4))) + 1
  RETURN @ISOweek
END
GO

(From windowsitpro.com)

Since SQL2008, DatePart supports the ISO Week, by calling:
DatePart(isowk, @date) or  DatePart(isoww, @date)