Execute Dynamic SQL commands in SQL Server

In some applications having hard-coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straightforward if you only need to pass parameters into the WHERE clause of your SQL statement. Let’s say we need to find all records from the Customers table where City = ‘London’. This can be done easily as the following example shows. ...

SQL Server Function to Determine a Leap Year

The following scalar function takes in a year and returns a bit flag indicating whether the passing year is a leap year or not.

create function dbo.fn_IsLeapYear (@year int) returns bit 
as 
	begin 
	return(select case datepart(mm, dateadd(dd, 1, cast((cast(@year as varchar(4)) + '0228') as datetime)))
	 when 2 then 1 
	 else 0 end) 
	 end 
	 go 

That’s all there is to it! The function takes in the year, appends ‘0228’ to it (for February 28th) and adds a day. If the month of the next day is a 2 (as extracted by the DATEPART function), then we’re still in February, so it must be a leap year! If not, it is not a leap year.

Here are a few examples:

select dbo.fn_IsLeapYear(1900) as 'IsLeapYear?' 
select dbo.fn_IsLeapYear(2000) as 'IsLeapYear?' 
select dbo.fn_IsLeapYear(2007) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2008) as 'IsLeapYear?'

Comments

Popular posts from this blog

Check If Temporary Table Exists

Multiple NULL values in a Unique index in SQL

How To search entire database?