DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
 
 
SITE SEARCH SQLUSA.com VIDEOS
 
 
SQL E/BOOKS   WORLD, USA & SQL NEWS   FORMAT
SCRIPTS SQL 2005 SQL 2008 ARTICLES
How to get results from a dynamic sql query?

Execute the following SQL Server T-SQL script in Management Studio Query Editor to demonstrate the use OUTPUT parameter in dynamic SQL query execution with sp_executesql system procedure.

 

-- SQL dynamic sql output parameter - SQL dynamic query output

USE AdventureWorks;

DECLARE  @SQL            NVARCHAR(1024),

         @ParmDefinition NVARCHAR(1024)

DECLARE  @FirstLetter   CHAR(1),

         @LastFirstName NVARCHAR(50)

 

SET @SQL = N'SELECT @LastFirstNameOUT = max(FirstName)      

      FROM Person.Contact' + CHAR(13) +

      'WHERE left(LastName,1) = @FirstLetterOfLastName'

 

SET @ParmDefinition = N'@FirstLetterOfLastName char(1),      

    @LastFirstNameOUT nvarchar(50) OUTPUT'

 

SET @FirstLetter = 'M'

 

PRINT @SQL + CHAR(13) -- testing & debugging

/*

SELECT @LastFirstNameOUT = max(FirstName)       FROM Person.Contact

WHERE left(LastName,1) = @FirstLetterOfLastName

*/

PRINT @ParmDefinition -- testing & debugging

/*

@FirstLetterOfLastName char(1),  @LastFirstNameOUT nvarchar(50) OUTPUT

*/

 

EXECUTE sp_executesql

  @SQL ,

  @ParmDefinition ,

  @FirstLetterOfLastName = @FirstLetter ,

  @LastFirstNameOUT = @LastFirstName OUTPUT

 

SELECT [Last First Name] = @LastFirstName,

       Legend = 'of last names starting with',

       Letter = @FirstLetter

 

GO

/* Result

 

Last First Name   Legend                        Letter

Zoe               of last names starting with   M

*/

Related article:

 

http://www.sqlusa.com/bestpractices/dynamicsql/

 

Exam Prep 70-461
SQL 2016 DESIGN & PROGRAMMING
 
 
 
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE