Tuesday, February 1, 2011

Building Statements at Run Time

Building Statements at Run Time: "EXEC sp_executesql @SQLString GO"

USE [MyDB]
SET DATEFORMAT DMY
GO
/****** Object:  StoredProcedure [dbo].[GetEventsByCriteria]    Script Date: 02/01/2011 21:01:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE [dbo].[GetEventsByCriteria]
(
  @EventStartDate nvarchar(25)
)

As
DECLARE @SQLString NVARCHAR(500)


/* Set column list. CHAR(13) is a carriage return, line feed.*/
SET @SQLString = N'SELECT * FROM EVENTS ' + CHAR(13)

/* Set WHERE clause. */
SET @SQLString = @SQLString + N' WHERE EventStartDate>=''' + @EventStartDate + ''''
-- CONVERT(datetime, @eventstartdate, 103)

/* Set ORDER clause. */
SET @SQLString = @SQLString + N' ORDER BY EventStartDate DESC'
-- CONVERT(datetime, @eventstartdate, 103)

EXEC sp_executesql @SQLString
--CONVERT(varchar(8), ctdate, 112)

No comments: