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 2005 Cast-Convert Date Time Format

Using CAST function in SQL Server 2005:

Syntax:

CAST (expression as datatype)

CAST function accepts expression name as column name or any SQL function that return expression or value and declare the datatype of the expression into which you want to cast/convert it.

Following are the SQL Server 2005 query syntax to cast DateTime into varchar:

E.g.:

USE Pubs

select cast(pubdate as varchar) from titles

or

select cast(getdate() as varchar)


Following are the MS SQL Server 2005 query Syntax to convert Time format:

SQL query to convert Time format into hh:mm:ss:

select convert(varchar, getdate(), 108)

SQL query to convert Time format into hh:mi:ss:mmm(24h):

select convert(varchar, getdate(), 114)

You can use datetime type column name instead of getdate() function.

E.g.:

USE PUBS

select convert(varchar,pubdate,108) from titles

or

select convert(varchar,pubdate,114) from titles



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?