3

Can some one please help me how can I pass a Parameter value into a string that is inside a Variable

Ex:

DECLARE @STR VARCHAR(MAX) = ''

DECLARE @ID INT

SET @STR = 'SELECT * FROM STUDENT WHERE STUDENT_ID=@ID'

Here I want to pass @ID as a parameter to Variable @STR

6 Answers 6

4

Use sp_executesql to value to the parameter this will also avoid sql injection. Try this

DECLARE @STR NVARCHAR(MAX) = ''

DECLARE @ID INT

SET @STR = 'SELECT * FROM STUDENT WHERE STUDENT_ID=@ID'

exec sp_executesql @str,'@ID INT',@ID
Sign up to request clarification or add additional context in comments.

2 Comments

to use sp_executesql sql statement must be a Unicode variable.. so @STR should be nvarchar else it will thow error..
@Mini - yep missed it
1

Use this:

DECLARE @STR VARCHAR(MAX) = ''

DECLARE @ID INT

SET @STR = 'SELECT * FROM STUDENT WHERE STUDENT_ID=' + CAST(@ID AS VARCHAR(50))

Comments

0

Here's one easy way:

DECLARE @STR VARCHAR(MAX) = ''

DECLARE @ID INT

SET @STR = 'SELECT * FROM STUDENT WHERE STUDENT_ID=@ID'

SET @STR = REPLACE(@STR, '@ID', COALESCE(CAST(@ID AS varchar(31)),''))

And of course there are others. You could have used string concatenation when building @STR, or you could keep it the way it is and use a parameterized call to sp_executesql when you finally want to execute the string, assuming that's what you want to do with it.

Comments

0

You can write a query as:

DECLARE @ID int;
--to use sp_executesql sql statement  must be a Unicode variable
DECLARE @STR nvarchar(500);     
DECLARE @ParmDefinition nvarchar(500);

/* Build the SQL string.
as a best practice you should specify column names instead of writing *
*/
SET @STR =
     N'SELECT Col1,Col2 FROM STUDENT WHERE STUDENT_ID=@ID';

SET @ParmDefinition = N'@ID Int';
/* Execute the string with the parameter value. */
SET @ID = 1;
EXECUTE sp_executesql @STR, @ParmDefinition,
                      @ID = @ID;

Comments

0

For simplicity you can also create a Store Procedure for it:-

Code in SQL

Create Proc [ProcedureName]
    @ID As int
As

SELECT * FROM STUDENT WHERE STUDENT_ID=@ID

Calling a Store Procedure

[ProcedureName] 1
--Here replace "1" with your Id

Comments

0

DECLARE @STR VARCHAR(MAX) = ''

DECLARE @ID INT

SET @STR = 'SELECT * FROM STUDENT WHERE STUDENT_ID='+@ID

should do

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.