SQL contains a command, EXEC (or EXECUTE), which can be used to dynamically execute a SQL statement. EXEC expects a string - the SQL statement you wish to execute. It will execute the SQL statement passed and returns the results.

Example:


CREATE PROCEDURE SP_GETELEMENTVALUESFORID
@ELEMENT varchar(100),
@EMPLOYEEID varchar(100)
AS
DECLARE @QUERY varchar(250)

IF(@ELEMENT = 'LOCATION')
SET @QUERY = 'SELECT DISTINCT LOCATION, TLOC.LOCATIONID From TBLLOCATION TLOC JOIN TBLACCESS TACC ON TLOC.LOCATIONID = TACC.LOCATIONID WHERE TACC.EMPLOYEEID = ' + @EMPLOYEEID
ELSE IF(@ELEMENT = 'VERTICAL')
SET @QUERY = 'SELECT DISTINCT VERTICAL, TVER.VERTICALID From TBLVERTICAL TVER JOIN TBLACCESS TACC ON TLOC.VERTICALID = TACC.VERTICALID WHERE TACC.EMPLOYEEID = ' + @EMPLOYEEID

EXEC (@QUERY)
GO

Do not Forget the bracket surrounding the @query. Without the brackets, you will get an error in when executing.

1 comments

  1. Suraj Shrestha // 11:42 AM  

    Hi , I am Suraj Shrestha from Nepal. I work as application programmer in Surya Nepal.

    I have also experimented with lot of lot of dynamic SQL. It's very beneficial. But it has got some drawbacks. It is slow as its execution plan is created at run time. However, using dynamic sql greately reduces the length of sql query.

    regards,
    Suraj
    http://bettercodes.blogspot.com