Click here to Skip to main content
Click here to Skip to main content

Tagged as

How to Assign Value to Parameters Used in Query which is Stored in a Variable

, 19 Nov 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
DECLARE
  /* @STRQUERY AND @PARAMDEF SHOULD BE NVARCHAR
     BECAUSE "EXECUTE sp_executesql" ACCEPTS STATEMENT AND PARAMETER OF TYPE 'ntext/nchar/nvarchar' ONLY
     OTHERWISE
     "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'."
     OR
     "Procedure expects parameter '@parameters' of type 'ntext/nchar/nvarchar'."  WILL BE RAISED*/
  @STRQUERY AS NVARCHAR(200),
  @STRNAME AS VARCHAR(100),
  @PARAMDEF AS NVARCHAR(100),
  @STRNAMEVALUE AS VARCHAR(100)
BEGIN
    --FOLLOWING STATEMENT ASSING VALUE
     SET @STRNAMEVALUE='MANINDER'
    --FOLLOWING VARIABLE CONTAINS A QUERY WHICH USES A PARAMETER
    SET @STRQUERY = 'SELECT ''YOUR NAME IS '' + @STRNAME'
    --FOLLOWING STATEMENT DEFINES THE PARAMETERS USED IN THE QUERY
    SET @PARAMDEF = '@STRNAME AS VARCHAR(100)'
    --IN THE FOLLOWING STATEMENT "@STRNAME = @STRNAMEVALUE" STATEMENT ASSIGNS VALUE TO THE PARAMETER
    --SYNTAX IS EXECUTE sp_executesql @STATEMENT, @PARAMETERS
    EXECUTE sp_executesql @STRQUERY, @PARAMDEF,@STRNAME = @STRNAMEVALUE;
END

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

shankeyshankey
Software Developer
India India
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 1 Nothing new; a simple link to the BO... PinmemberRichard Deeming24-Nov-10 9:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141030.1 | Last Updated 19 Nov 2010
Article Copyright 2010 by shankeyshankey
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid