May 10, 2012 at 6:43 am
I am urgently in need of some help. My colleague and I have developed a script (that works) but uses Hard coded values. I have used the EXEC command before but not to assign a value to a variable.
eg:
SET @noOfCopies = (select SUM(NoOfCopies) as 'NumberOfCopies' FROM importedStats
Where
AuthorityCode=659 and
Category in ('AF','Jf') and Binding in ('P')
and dateImported between '01/05/2012' and '02/05/2012'
and libraryPolicyname = 'brixm'
)
The authority Code will change and I might not know the Category or the binding maybe different and it may not have an import date.
How can I build the string and assign the value to the variable
Many thanks
Darryl Wilson
darrylw99@hotmail.com
May 10, 2012 at 7:11 am
You should be using sp_executesql rather than EXEC. BOL has examples of using parameters including OUTPUT parameters.
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA
May 10, 2012 at 7:11 am
Have a look at sp_executesql in BOL.
May 10, 2012 at 7:12 am
May 10, 2012 at 7:41 am
I am using the sp_ExeceuteSQL but how do i assign the value of the executed sql to a variable (so that i can use it further down the script)
Darryl Wilson
darrylw99@hotmail.com
May 10, 2012 at 8:04 am
Here is an example:
DECLARE @ReturnValue int
DECLARE @SqlStmt nvarchar ( 1024 )
DECLARE @MyParams nvarchar ( 1024 )
SET @SqlStmt = N'SELECT @CountOfRows = COUNT(*) FROM sys.objects'
SET @MyParams = N'@CountOfRows int OUTPUT'
EXEC sp_executesql @statement = @SqlStmt,
@params = @MyParams,
@CountOfRows = @ReturnValue OUTPUT
SELECT @ReturnValue
Edit: Since the parameters to sp_executesql are all Nvarchar, I might as well explicity make the constants Nvarchar as well 😉 And made the parameter names passed to sp_executesql different to the ones in the dynamic SQL statement to make it more clear what's what.
May 10, 2012 at 3:20 pm
Darryl, did this help at all? If not, please come back and ask, we're all happy to assist.
May 10, 2012 at 5:58 pm
None of what you seek to do actually requires any form of dynamic SQL from what I can see.
--Jeff Moden
Change is inevitable... Change for the better is not.
May 11, 2012 at 3:00 am
use sp_executesql
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply