T-SQL Syntax for return values from stored procedures
-
Friday, March 30, 2012 10:50 PM
Hi there, I cannot get this to work. Why is nothing print in the following SQL? Please note I use dynamic SQL in the stored procedure.
if object_id('usp_Do_Some', 'P') is not null drop proc usp_Do_Some ; go create proc usp_Do_Some @RetVal as nvarchar(20) output as declare @SQLQuery as nvarchar(max) set @SQLQuery = ' select ' + @RetVal + ' = ''hello'';' exec (@SQLQuery) ; go declare @String as nvarchar(20) exec usp_Do_Some @RetVal = @String output; print @StringThanks in advance!
Christian
All Replies
-
Friday, March 30, 2012 11:11 PMModerator
Here is the corrected dynamic SQL syntax:
IF Object_id('usp_Do_Some', 'P') IS NOT NULL DROP PROC usp_do_some; GO CREATE PROC Usp_do_some @RetVal AS NVARCHAR(20) OUTPUT AS DECLARE @SQLQuery AS NVARCHAR(MAX) DECLARE @ParmDefinition NVARCHAR(1024)= N'@pRetVal as nvarchar(20) output' SET @SQLQuery = ' select @pRetVal = ''hello'';' EXEC Sp_executesql @SQLQuery, @ParmDefinition, @pRetVal= @RetVal OUTPUT; GO DECLARE @String AS NVARCHAR(20) EXEC Usp_do_some @RetVal = @String OUTPUT; PRINT @String -- hello GODynamic SQL article:
http://www.sqlusa.com/bestpractices/dynamicsql/
Kalman Toth SQL SERVER & BI TRAINING
- Proposed As Answer by Naomi NMicrosoft Community Contributor, Moderator Friday, March 30, 2012 11:13 PM
- Marked As Answer by chhenning Monday, April 02, 2012 1:52 PM
-
Monday, April 02, 2012 1:54 PMThank you very much!

