Thursday, June 19, 2014

Drop FOREIGN KEY constraint from all table of database

while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
       declare @sql nvarchar(2000)
       SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
       + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
       FROM information_schema.table_constraints
       WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
       exec (@sql)
end



Wednesday, June 4, 2014

Get week start date and week end date of a month in SQL server



#First week of particular month will be start from 1st day of month and last week of month will be end at month end date    

    with C(i) as
              ( select CONVERT(VARCHAR(10),CAST(@monthStart as datetime),111) i
                UNION ALL
                select CONVERT(VARCHAR(10),DATEADD (day,1,i),111) i from C
                     where DATEADD (day,1,i)
                             <DATEADD(month,1,@monthStart)
              ), C1 as
              (
              select DATEPART(WEEK,i)-DATEPART(WEEK,@monthStart)+1 WeekOfMonth,i from C
              )
              select WeekOfMonth,min(i) StartDate, max(i) EndDate from C1 group by WeekOfMonth