How to execute string (custom built sql query ) in a stored procedure

sp_executesql executes string in a stored procedure. It is used in more complex queries which we need to build concatenating strings. The string is run as a batch. The following example gets the TOP records from a table matching predefined conditions.

CREATE PROCEDURE [GetTOPRecords]
@count varchar(6),
@conditions nvarchar(300)
AS
BEGIN

DECLARE @SQL nvarchar(1000)

SET
@SQL='SELECT
TOP '+ @count + ' * FROM RecordsTable
WHERE ' + @conditions

EXEC sp_executesql @SQL

END


The @count and @conditions are passed as parameters. The execution string is built run-time and executed. If you don't need any conditions here just pass the string ' 1=1 ' as @conditions.

No comments:

Post a Comment