Thursday, March 29, 2012

find the last day of the month. Query also take care of Leap Year.

Following query will find the last day of the month. Query also take care of Leap Year.

Script:

DECLARE @date DATETIME

SET @date='2008-02-03'

SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)), DATEADD(m,1,@date))

            AS LastDayOfMonth

 

ResultSet:

LastDayOfMonth

-----------------------

2008-02-29 00:00:00.000

 

GO

DECLARE @date DATETIME

    SET @date='2007-02-03'

SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)), DATEADD(m,1,@date))

            AS LastDayOfMonth

ResultSet:

LastDayOfMonth

-----------------------

2007-02-28 00:00:00.000


Last Day of month

Last Day of Month


----Last Day of Privious Month

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))

LastDay_PreviousMonth

----Last Day of Current Month

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))

LastDay_CurrentMonth

----Last Day of Next Month

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))




Wednesday, March 28, 2012

Find out a character or Number from string.

Following SQL User Defined Function will extract/parse numbers from the string.

 

CREATE FUNCTION ExtractInteger(@String VARCHAR(2000))

RETURNS VARCHAR(1000)

AS

BEGIN

DECLARE @Count INT

DECLARE @IntNumbers VARCHAR(1000)

SET @Count = 0

SET @IntNumbers = ''

 

WHILE @Count <= LEN(@String)

BEGIN

IF SUBSTRING(@String,@Count,1) between '0' and '9'

BEGIN

SET @IntNumbers = @IntNumbers + SUBSTRING(@String,@Count,1)

END

SET @Count = @Count + 1

END

RETURN @IntNumbers

END

GO

 

Execute this

SELECT dbo.ExtractInteger('My birthday date 06-06-1987')GO

Tuesday, March 27, 2012

Select a table dynamically in a database using passing a parameter tablename

declare @tablename varchar(50)

declare @cursor cursor

set @cursor=CURSOr for

select table_Name from information_schema.tables 

where table_type='base table'

open @cursor

fetch next

from @cursor into @tablename

while @@FETCH_STATUS=0

begin

declare @sql varchar(500)

set @sql = 'select * from ' + @tablename

exec (@sql)

fetch next

from @cursor into @tablename

end

close @cursor

deallocate @cursor


Monday, March 26, 2012

Display date it differ year,month,week and date parameter

declare @no int,@date datetime=GETDATE()

declare @yy varchar(5)='2012',@mm varchar(2)='03',@week int=4,

@day varchar(2)='2'

select @date=@yy+'-'+@mm+'-'+'01'

select @no=DATEPART(WEEKDAY,@date)

if @no in(1,2)

select @date-(@no-2)

else

begin

select dateadd(ww,@week,@date)-(@no-@day)

end



Find out Month start date and end date

declare @date datetime='2012-03-26 18:25:59.620'

Declare @month int,@year int,@startdate datetime,@enddate datetime,@vdate datetime,@count int

select @month=MONTH(@date),@year=YEAR(@date)

select @startdate=cast(@year as varchar)+'-'+cast(@month as varchar)+'-'+'01'

select @vdate=DATEADD(mm,1,@startdate)

select @count=DATEDIFF(DAY,@startdate,@vdate)

select @enddate=DATEADD(day,@count-1,@startdate)

select @startdate as startdate,@enddate  as enddate,datename(DW,@startdate) as startdatename,datename(dw,@enddate) as enddatename


Wednesday, March 14, 2012

Bulk insert using Select

SELECT a,b,c

FROM (VALUES

        (1, '20010101','A'),

        (3, '20020101','B'),

        (5, '20030101','C'),

        (7, '20040101','D'),

        (9, '20050101','E') ) AS SomeTable(a, b,c);

Linked server Query

/****** Object:  LinkedServer [10.200.2.54\sqlexpress]    Script Date: 03/12/2012 12:07:14 ******/

EXEC master.dbo.sp_addlinkedserver @server = N'192.168.20.1\sqlexpress', @srvproduct=N'SQL Server'

 /* For security reasons the linked server remote logins password is changed with ######## */

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'192.168.20.1\sqlexpress',@useself=N'False',@locallogin=NULL,@rmtuser=N'USERNAME',@rmtpassword='PASSWORD'

 

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'collation compatible', @optvalue=N'false'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'data access', @optvalue=N'true'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'dist', @optvalue=N'false'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'pub', @optvalue=N'false'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'rpc', @optvalue=N'true'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'rpc out', @optvalue=N'true'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'sub', @optvalue=N'false'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'connect timeout', @optvalue=N'0'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'collation name', @optvalue=null

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'lazy schema validation', @optvalue=N'false'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'query timeout', @optvalue=N'0'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'use remote collation', @optvalue=N'true'

GO

 

EXEC master.dbo.sp_serveroption @server=N'192.168.20.1\sqlexpress', @optname=N'remote proc transaction promotion', @optvalue=N'true'

GO 

 

TRY_CATCH

TRY- CATCH
 
TRY block and you check for the errors in the CATCH block. SQL Server has a bunch of functions that will help you identify why your code failed, here is a list of the functions and what they return
 
ERROR_NUMBER()
 
returns the number of the error
 
ERROR_SEVERITY()
 
returns the severity of the error
 
ERROR_STATE()
 
returns the error state number
 
ERROR_PROCEDURE()
 
returns the name of the stored procedure or trigger where the error occurred, this will be NULL if you run an ad-hoc SQL statement
 
ERROR_LINE()
 
returns the line number inside the routine that caused the error
 
ERROR_MESSAGE()
 

returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times

Let's run an example that generates a divide by zero error, in the catch we are just doing a simple select that calls the functions mentioned before to see what they return

BEGIN TRY

    --  divide-by-zero error.

    SELECT 1/0

END TRY

BEGIN CATCH

    SELECT

    ERROR_NUMBER() AS ErrorNumber

    ,ERROR_SEVERITY() AS ErrorSeverity

    ,ERROR_STATE() AS ErrorState

    ,ERROR_PROCEDURE() AS ErrorProcedure

    ,ERROR_LINE() AS ErrorLine

    ,ERROR_MESSAGE() AS ErrorMessage;

END CATCH;

output

ErrorNumber

ErrorSeverity

ErrorState

ErrorProcedure

ErrorLine

ErrorMessage

8134

16

1

NULL

3

Divide by zero error encountered.

 
 
As you can see we got all that information back, that was pretty nice. Let's take it to the next step
Create the following table to store all the error information in
 

CREATE TABLE LogErrors (ErrorTime datetime,

            ErrorNumber int,

            ErrorSeverity int,

            ErrorState int,

            ErrorProc nvarchar(100),

            ErrorLine int,

            ErrorMessage nvarchar(1000))

GO

Create this stored procedure that will insert into the table we just created

 

CREATE PROCEDURE prInsertError

AS

INSERT LogErrors

SELECT GETDATE(),

    ERROR_NUMBER(),

    ERROR_SEVERITY(),

    ERROR_STATE(),

    ERROR_PROCEDURE(),

    ERROR_LINE(),

    ERROR_MESSAGE() ;

GO

Run these 3 queries, they will generate 3 inserts into the LogErrors tableBEGIN TRY

    SELECT 1/0

END TRY

BEGIN CATCH

    EXEC prInsertError

END CATCH;

 

 

BEGIN TRY

    SELECT convert(int,'a')

END TRY

BEGIN CATCH

    EXEC prInsertError

END CATCH;

 

BEGIN TRY

    SELECT convert(tinyint,300)

END TRY

BEGIN CATCH

    EXEC prInsertError

END CATCH;

--// Error Output..

SELECT * FROM LogErrors

 

ErrorTime

ErrorNumber

ErrorSeverity

ErrorState

ErrorProc

ErrorLine

ErrorMessage

14-Mar-12

8134

16

1

NULL

2

Divide by zero error encountered.

14-Mar-12

245

16

1

NULL

10

Conversion failed when converting the varchar value 'a' to data type int.

14-Mar-12

220

16

2

NULL

18

Arithmetic overflow error for data type tinyint, value = 300.

 

 


Thursday, March 8, 2012

Displaying date from Two different in between Date.

declare @diff int,

@start_date datetime='2012-03-08 00:00:00.000',

@end_date datetime='2012-03-14 00:00:00.000'

declare @table table

(DateValue datetime)

set @diff =(select  datediff(day,@start_date,@end_date)) 

--select @diff 

declare @Flag int=0 

WHILE (@Flag <= @diff) 

BEGIN 

insert into @table   select DATEADD(day,@Flag,@start_date) 

 

--PRINT @Flag 

SET @Flag = @Flag + 1 

END 

select * from @table

Output

DateValue

03/08/12

03/09/12

03/10/12

03/11/12

03/12/12

03/13/12

03/14/12