Set in dynamic query value of variable declared outside dynamic queryScript to query multiple instancesHandling exceptions in stored procedures called using insert-exec blocksRun Multiple Remote JobsOracle GoldenGate add trandata errorsIs there any way to access the variables in a dynamic sql which is declared outside the dynamic sqlRound-robin T-SQL problem with a twistGroup By With Rollup results table has totals at the topRetrieve value of select query in a table columnInvestigating errors from strange queryHow to have more than 100 entries in case statement as a variable

How to make money from a browser who sees 5 seconds into the future of any web page?

Will number of steps recorded on FitBit/any fitness tracker add up distance in PokemonGo?

15% tax on $7.5k earnings. Is that right?

What to do when eye contact makes your coworker uncomfortable?

How can ping know if my host is down

Find the next value of this number series

Is there a nicer/politer/more positive alternative for "negates"?

What is the English pronunciation of "pain au chocolat"?

Creating two special characters

Stack Interview Code methods made from class Node and Smart Pointers

Why is so much work done on numerical verification of the Riemann Hypothesis?

A variation to the phrase "hanging over my shoulders"

Permission on Database

Which was the first story featuring espers?

Which Article Helped Get Rid of Technobabble in RPGs?

How does electrical safety system work on ISS?

Can I turn my anal-retentiveness into a career?

Why is the "ls" command showing permissions of files in a FAT32 partition?

How to explain what's wrong with this application of the chain rule?

How to draw a matrix with arrows in limited space

Is there a RAID 0 Equivalent for RAM?

Can I cause damage to electrical appliances by unplugging them when they are turned on?

US tourist/student visa

Is it allowed to activate the ability of multiple planeswalkers in a single turn?



Set in dynamic query value of variable declared outside dynamic query


Script to query multiple instancesHandling exceptions in stored procedures called using insert-exec blocksRun Multiple Remote JobsOracle GoldenGate add trandata errorsIs there any way to access the variables in a dynamic sql which is declared outside the dynamic sqlRound-robin T-SQL problem with a twistGroup By With Rollup results table has totals at the topRetrieve value of select query in a table columnInvestigating errors from strange queryHow to have more than 100 entries in case statement as a variable













1















I have a stored procedure which i simplified this way :



DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT

SET @variable2 = 1
SET '+CAST(@variable1 AS VARCHAR)+' = @variable2

SELECT @variable1 as V1, @variable2 as V2
'
EXEC(@SQL)


But this script don't give me anything ! I'm pretty sure it's something related to scope. The thing is that i need to declare the variable outside the dynamic query.



thanks for help !



EDIT :



WHILE LOOP UNTIL SELECT COUNT xxx = 0
BEGIN
DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
EXEC STORE PROC WITH PARAMETER @Param1 = @variable1 (first loop @Param1 is null)

STORE PROC RETURN A VALUE

SET @variable1 with return value of store proc
and use it in second loop, third loop...
'
EXEC(@SQL)
END









share|improve this question



















  • 2





    Your @variable1 is null in this script; so, this : SET '+CAST(@variable1 AS VARCHAR)+... will be null ; ps: CAST(AS VARCHAR) should be always CAST(AS VARCHAR(XX))

    – Sabin Bio
    11 hours ago












  • ok but is there a way to go over that ?

    – Matthieu RGX
    11 hours ago











  • you should provide more details; you could initialize it with a value : DECLARE @variable1 INT =0

    – Sabin Bio
    11 hours ago












  • you mean initialize the value inside the dynamic query or outside ? i will try to edit my question to provide more details !

    – Matthieu RGX
    11 hours ago






  • 1





    i've edit my question !

    – Matthieu RGX
    11 hours ago















1















I have a stored procedure which i simplified this way :



DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT

SET @variable2 = 1
SET '+CAST(@variable1 AS VARCHAR)+' = @variable2

SELECT @variable1 as V1, @variable2 as V2
'
EXEC(@SQL)


But this script don't give me anything ! I'm pretty sure it's something related to scope. The thing is that i need to declare the variable outside the dynamic query.



thanks for help !



EDIT :



WHILE LOOP UNTIL SELECT COUNT xxx = 0
BEGIN
DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
EXEC STORE PROC WITH PARAMETER @Param1 = @variable1 (first loop @Param1 is null)

STORE PROC RETURN A VALUE

SET @variable1 with return value of store proc
and use it in second loop, third loop...
'
EXEC(@SQL)
END









share|improve this question



















  • 2





    Your @variable1 is null in this script; so, this : SET '+CAST(@variable1 AS VARCHAR)+... will be null ; ps: CAST(AS VARCHAR) should be always CAST(AS VARCHAR(XX))

    – Sabin Bio
    11 hours ago












  • ok but is there a way to go over that ?

    – Matthieu RGX
    11 hours ago











  • you should provide more details; you could initialize it with a value : DECLARE @variable1 INT =0

    – Sabin Bio
    11 hours ago












  • you mean initialize the value inside the dynamic query or outside ? i will try to edit my question to provide more details !

    – Matthieu RGX
    11 hours ago






  • 1





    i've edit my question !

    – Matthieu RGX
    11 hours ago













1












1








1








I have a stored procedure which i simplified this way :



DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT

SET @variable2 = 1
SET '+CAST(@variable1 AS VARCHAR)+' = @variable2

SELECT @variable1 as V1, @variable2 as V2
'
EXEC(@SQL)


But this script don't give me anything ! I'm pretty sure it's something related to scope. The thing is that i need to declare the variable outside the dynamic query.



thanks for help !



EDIT :



WHILE LOOP UNTIL SELECT COUNT xxx = 0
BEGIN
DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
EXEC STORE PROC WITH PARAMETER @Param1 = @variable1 (first loop @Param1 is null)

STORE PROC RETURN A VALUE

SET @variable1 with return value of store proc
and use it in second loop, third loop...
'
EXEC(@SQL)
END









share|improve this question
















I have a stored procedure which i simplified this way :



DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT

SET @variable2 = 1
SET '+CAST(@variable1 AS VARCHAR)+' = @variable2

SELECT @variable1 as V1, @variable2 as V2
'
EXEC(@SQL)


But this script don't give me anything ! I'm pretty sure it's something related to scope. The thing is that i need to declare the variable outside the dynamic query.



thanks for help !



EDIT :



WHILE LOOP UNTIL SELECT COUNT xxx = 0
BEGIN
DECLARE @variable1 INT

DECLARE @SQL VARCHAR(MAX)

SET @SQL = '
EXEC STORE PROC WITH PARAMETER @Param1 = @variable1 (first loop @Param1 is null)

STORE PROC RETURN A VALUE

SET @variable1 with return value of store proc
and use it in second loop, third loop...
'
EXEC(@SQL)
END






sql-server t-sql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 11 hours ago







Matthieu RGX

















asked 11 hours ago









Matthieu RGXMatthieu RGX

246




246







  • 2





    Your @variable1 is null in this script; so, this : SET '+CAST(@variable1 AS VARCHAR)+... will be null ; ps: CAST(AS VARCHAR) should be always CAST(AS VARCHAR(XX))

    – Sabin Bio
    11 hours ago












  • ok but is there a way to go over that ?

    – Matthieu RGX
    11 hours ago











  • you should provide more details; you could initialize it with a value : DECLARE @variable1 INT =0

    – Sabin Bio
    11 hours ago












  • you mean initialize the value inside the dynamic query or outside ? i will try to edit my question to provide more details !

    – Matthieu RGX
    11 hours ago






  • 1





    i've edit my question !

    – Matthieu RGX
    11 hours ago












  • 2





    Your @variable1 is null in this script; so, this : SET '+CAST(@variable1 AS VARCHAR)+... will be null ; ps: CAST(AS VARCHAR) should be always CAST(AS VARCHAR(XX))

    – Sabin Bio
    11 hours ago












  • ok but is there a way to go over that ?

    – Matthieu RGX
    11 hours ago











  • you should provide more details; you could initialize it with a value : DECLARE @variable1 INT =0

    – Sabin Bio
    11 hours ago












  • you mean initialize the value inside the dynamic query or outside ? i will try to edit my question to provide more details !

    – Matthieu RGX
    11 hours ago






  • 1





    i've edit my question !

    – Matthieu RGX
    11 hours ago







2




2





Your @variable1 is null in this script; so, this : SET '+CAST(@variable1 AS VARCHAR)+... will be null ; ps: CAST(AS VARCHAR) should be always CAST(AS VARCHAR(XX))

– Sabin Bio
11 hours ago






Your @variable1 is null in this script; so, this : SET '+CAST(@variable1 AS VARCHAR)+... will be null ; ps: CAST(AS VARCHAR) should be always CAST(AS VARCHAR(XX))

– Sabin Bio
11 hours ago














ok but is there a way to go over that ?

– Matthieu RGX
11 hours ago





ok but is there a way to go over that ?

– Matthieu RGX
11 hours ago













you should provide more details; you could initialize it with a value : DECLARE @variable1 INT =0

– Sabin Bio
11 hours ago






you should provide more details; you could initialize it with a value : DECLARE @variable1 INT =0

– Sabin Bio
11 hours ago














you mean initialize the value inside the dynamic query or outside ? i will try to edit my question to provide more details !

– Matthieu RGX
11 hours ago





you mean initialize the value inside the dynamic query or outside ? i will try to edit my question to provide more details !

– Matthieu RGX
11 hours ago




1




1





i've edit my question !

– Matthieu RGX
11 hours ago





i've edit my question !

– Matthieu RGX
11 hours ago










1 Answer
1






active

oldest

votes


















5














Three things worth mentioning:




  • Always use PRINT to view the resulting dynamic SQL whenever you work with dynamic SQL. You will see that the SQL variable is actually holding NULL.



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET ' + CAST(@variable1 AS VARCHAR) + ' = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)

    -- EXEC(@SQL)


enter image description here




  • The reason because the dynamic SQL is NULL is because you are concatenating a NULL value which is the @variable1 contents. I believe you wanted to write down the text '@variable1' as literal:



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET @variable1 = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)


enter image description here



  • Whenever you use EXEC, the scope changes and variables declared outside can't be accessed anymore. So inside the dynamic SQL, you won't be able to read @variable1 since it's not declare anywhere. If we execute the dynamic SQL:

enter image description here




The way you can set variables values inside a dynamic execution and be able to read them from the outside is by supplying parameters via the OUTPUT option. This will require to use the SP sp_executesql rathen than a direct EXEC:



DECLARE @externalVariable INT

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT = 1
SET @resultVariable = @variable2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'@resultVariable INT OUTPUT', -- Declare the "input" parameters for the dynamic SQL
@resultVariable = @externalVariable OUTPUT -- Supply the "input" parameters for the dynamic SQL

SELECT
Result = @externalVariable -- Read the updated value


Note that I changed data types to NVARCHAR since sp_executesql works with unicode inputs.



Another example with more parameters:



DECLARE @firstNumber INT = 15
DECLARE @secondNumber INT = 3
DECLARE @result INT

DECLARE @SQL NVARCHAR(MAX) = '
SET @multiplicationResult = @inputFactor1 * @inputFactor2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'
@multiplicationResult INT OUTPUT,
@inputFactor1 INT,
@inputFactor2 INT',
@multiplicationResult = @result OUTPUT,
@inputFactor1 = @firstNumber,
@inputFactor2 = @secondNumber

SELECT
Result = @result -- 45!


If you don't have to read back results from variables, you can build your dynamic SQL by "hard-coding" the variables values directly into the script. Make sure to correctly use data type conversions inside the script and also escape NULL and literal values:



DECLARE @DateVariable DATETIME = GETDATE()
DECLARE @StringVariable VARCHAR(100) = NULL
DECLARE @FloatVariable FLOAT = 15.14

DECLARE @DynamicSQL VARCHAR(MAX) = '
SELECT
DateVariableContents = CONVERT(DATETIME, ''' + ISNULL(CONVERT(VARCHAR(100), @DateVariable), '') + '''),
StringVariableContents = ' + ISNULL('''' + @StringVariable + '''', '''''') + ',
FloatVariableContents = CONVERT(FLOAT, ''' + ISNULL(CONVERT(VARCHAR(100), @FloatVariable), '') + ''') '

PRINT(@DynamicSQL)

EXEC(@DynamicSQL)


Printed:



SELECT
DateVariableContents = CONVERT(DATETIME, 'Mar 21 2019 3:27PM'),
StringVariableContents = '',
FloatVariableContents = CONVERT(FLOAT, '15.124')


Result:



DateVariableContents StringVariableContents FloatVariableContents
2019-03-21 15:28:00.000 15.124





share|improve this answer

























  • thanks a lot for your answer ! i will check it out and come back to you !

    – Matthieu RGX
    10 hours ago










Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f232722%2fset-in-dynamic-query-value-of-variable-declared-outside-dynamic-query%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









5














Three things worth mentioning:




  • Always use PRINT to view the resulting dynamic SQL whenever you work with dynamic SQL. You will see that the SQL variable is actually holding NULL.



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET ' + CAST(@variable1 AS VARCHAR) + ' = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)

    -- EXEC(@SQL)


enter image description here




  • The reason because the dynamic SQL is NULL is because you are concatenating a NULL value which is the @variable1 contents. I believe you wanted to write down the text '@variable1' as literal:



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET @variable1 = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)


enter image description here



  • Whenever you use EXEC, the scope changes and variables declared outside can't be accessed anymore. So inside the dynamic SQL, you won't be able to read @variable1 since it's not declare anywhere. If we execute the dynamic SQL:

enter image description here




The way you can set variables values inside a dynamic execution and be able to read them from the outside is by supplying parameters via the OUTPUT option. This will require to use the SP sp_executesql rathen than a direct EXEC:



DECLARE @externalVariable INT

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT = 1
SET @resultVariable = @variable2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'@resultVariable INT OUTPUT', -- Declare the "input" parameters for the dynamic SQL
@resultVariable = @externalVariable OUTPUT -- Supply the "input" parameters for the dynamic SQL

SELECT
Result = @externalVariable -- Read the updated value


Note that I changed data types to NVARCHAR since sp_executesql works with unicode inputs.



Another example with more parameters:



DECLARE @firstNumber INT = 15
DECLARE @secondNumber INT = 3
DECLARE @result INT

DECLARE @SQL NVARCHAR(MAX) = '
SET @multiplicationResult = @inputFactor1 * @inputFactor2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'
@multiplicationResult INT OUTPUT,
@inputFactor1 INT,
@inputFactor2 INT',
@multiplicationResult = @result OUTPUT,
@inputFactor1 = @firstNumber,
@inputFactor2 = @secondNumber

SELECT
Result = @result -- 45!


If you don't have to read back results from variables, you can build your dynamic SQL by "hard-coding" the variables values directly into the script. Make sure to correctly use data type conversions inside the script and also escape NULL and literal values:



DECLARE @DateVariable DATETIME = GETDATE()
DECLARE @StringVariable VARCHAR(100) = NULL
DECLARE @FloatVariable FLOAT = 15.14

DECLARE @DynamicSQL VARCHAR(MAX) = '
SELECT
DateVariableContents = CONVERT(DATETIME, ''' + ISNULL(CONVERT(VARCHAR(100), @DateVariable), '') + '''),
StringVariableContents = ' + ISNULL('''' + @StringVariable + '''', '''''') + ',
FloatVariableContents = CONVERT(FLOAT, ''' + ISNULL(CONVERT(VARCHAR(100), @FloatVariable), '') + ''') '

PRINT(@DynamicSQL)

EXEC(@DynamicSQL)


Printed:



SELECT
DateVariableContents = CONVERT(DATETIME, 'Mar 21 2019 3:27PM'),
StringVariableContents = '',
FloatVariableContents = CONVERT(FLOAT, '15.124')


Result:



DateVariableContents StringVariableContents FloatVariableContents
2019-03-21 15:28:00.000 15.124





share|improve this answer

























  • thanks a lot for your answer ! i will check it out and come back to you !

    – Matthieu RGX
    10 hours ago















5














Three things worth mentioning:




  • Always use PRINT to view the resulting dynamic SQL whenever you work with dynamic SQL. You will see that the SQL variable is actually holding NULL.



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET ' + CAST(@variable1 AS VARCHAR) + ' = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)

    -- EXEC(@SQL)


enter image description here




  • The reason because the dynamic SQL is NULL is because you are concatenating a NULL value which is the @variable1 contents. I believe you wanted to write down the text '@variable1' as literal:



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET @variable1 = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)


enter image description here



  • Whenever you use EXEC, the scope changes and variables declared outside can't be accessed anymore. So inside the dynamic SQL, you won't be able to read @variable1 since it's not declare anywhere. If we execute the dynamic SQL:

enter image description here




The way you can set variables values inside a dynamic execution and be able to read them from the outside is by supplying parameters via the OUTPUT option. This will require to use the SP sp_executesql rathen than a direct EXEC:



DECLARE @externalVariable INT

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT = 1
SET @resultVariable = @variable2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'@resultVariable INT OUTPUT', -- Declare the "input" parameters for the dynamic SQL
@resultVariable = @externalVariable OUTPUT -- Supply the "input" parameters for the dynamic SQL

SELECT
Result = @externalVariable -- Read the updated value


Note that I changed data types to NVARCHAR since sp_executesql works with unicode inputs.



Another example with more parameters:



DECLARE @firstNumber INT = 15
DECLARE @secondNumber INT = 3
DECLARE @result INT

DECLARE @SQL NVARCHAR(MAX) = '
SET @multiplicationResult = @inputFactor1 * @inputFactor2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'
@multiplicationResult INT OUTPUT,
@inputFactor1 INT,
@inputFactor2 INT',
@multiplicationResult = @result OUTPUT,
@inputFactor1 = @firstNumber,
@inputFactor2 = @secondNumber

SELECT
Result = @result -- 45!


If you don't have to read back results from variables, you can build your dynamic SQL by "hard-coding" the variables values directly into the script. Make sure to correctly use data type conversions inside the script and also escape NULL and literal values:



DECLARE @DateVariable DATETIME = GETDATE()
DECLARE @StringVariable VARCHAR(100) = NULL
DECLARE @FloatVariable FLOAT = 15.14

DECLARE @DynamicSQL VARCHAR(MAX) = '
SELECT
DateVariableContents = CONVERT(DATETIME, ''' + ISNULL(CONVERT(VARCHAR(100), @DateVariable), '') + '''),
StringVariableContents = ' + ISNULL('''' + @StringVariable + '''', '''''') + ',
FloatVariableContents = CONVERT(FLOAT, ''' + ISNULL(CONVERT(VARCHAR(100), @FloatVariable), '') + ''') '

PRINT(@DynamicSQL)

EXEC(@DynamicSQL)


Printed:



SELECT
DateVariableContents = CONVERT(DATETIME, 'Mar 21 2019 3:27PM'),
StringVariableContents = '',
FloatVariableContents = CONVERT(FLOAT, '15.124')


Result:



DateVariableContents StringVariableContents FloatVariableContents
2019-03-21 15:28:00.000 15.124





share|improve this answer

























  • thanks a lot for your answer ! i will check it out and come back to you !

    – Matthieu RGX
    10 hours ago













5












5








5







Three things worth mentioning:




  • Always use PRINT to view the resulting dynamic SQL whenever you work with dynamic SQL. You will see that the SQL variable is actually holding NULL.



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET ' + CAST(@variable1 AS VARCHAR) + ' = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)

    -- EXEC(@SQL)


enter image description here




  • The reason because the dynamic SQL is NULL is because you are concatenating a NULL value which is the @variable1 contents. I believe you wanted to write down the text '@variable1' as literal:



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET @variable1 = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)


enter image description here



  • Whenever you use EXEC, the scope changes and variables declared outside can't be accessed anymore. So inside the dynamic SQL, you won't be able to read @variable1 since it's not declare anywhere. If we execute the dynamic SQL:

enter image description here




The way you can set variables values inside a dynamic execution and be able to read them from the outside is by supplying parameters via the OUTPUT option. This will require to use the SP sp_executesql rathen than a direct EXEC:



DECLARE @externalVariable INT

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT = 1
SET @resultVariable = @variable2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'@resultVariable INT OUTPUT', -- Declare the "input" parameters for the dynamic SQL
@resultVariable = @externalVariable OUTPUT -- Supply the "input" parameters for the dynamic SQL

SELECT
Result = @externalVariable -- Read the updated value


Note that I changed data types to NVARCHAR since sp_executesql works with unicode inputs.



Another example with more parameters:



DECLARE @firstNumber INT = 15
DECLARE @secondNumber INT = 3
DECLARE @result INT

DECLARE @SQL NVARCHAR(MAX) = '
SET @multiplicationResult = @inputFactor1 * @inputFactor2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'
@multiplicationResult INT OUTPUT,
@inputFactor1 INT,
@inputFactor2 INT',
@multiplicationResult = @result OUTPUT,
@inputFactor1 = @firstNumber,
@inputFactor2 = @secondNumber

SELECT
Result = @result -- 45!


If you don't have to read back results from variables, you can build your dynamic SQL by "hard-coding" the variables values directly into the script. Make sure to correctly use data type conversions inside the script and also escape NULL and literal values:



DECLARE @DateVariable DATETIME = GETDATE()
DECLARE @StringVariable VARCHAR(100) = NULL
DECLARE @FloatVariable FLOAT = 15.14

DECLARE @DynamicSQL VARCHAR(MAX) = '
SELECT
DateVariableContents = CONVERT(DATETIME, ''' + ISNULL(CONVERT(VARCHAR(100), @DateVariable), '') + '''),
StringVariableContents = ' + ISNULL('''' + @StringVariable + '''', '''''') + ',
FloatVariableContents = CONVERT(FLOAT, ''' + ISNULL(CONVERT(VARCHAR(100), @FloatVariable), '') + ''') '

PRINT(@DynamicSQL)

EXEC(@DynamicSQL)


Printed:



SELECT
DateVariableContents = CONVERT(DATETIME, 'Mar 21 2019 3:27PM'),
StringVariableContents = '',
FloatVariableContents = CONVERT(FLOAT, '15.124')


Result:



DateVariableContents StringVariableContents FloatVariableContents
2019-03-21 15:28:00.000 15.124





share|improve this answer















Three things worth mentioning:




  • Always use PRINT to view the resulting dynamic SQL whenever you work with dynamic SQL. You will see that the SQL variable is actually holding NULL.



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET ' + CAST(@variable1 AS VARCHAR) + ' = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)

    -- EXEC(@SQL)


enter image description here




  • The reason because the dynamic SQL is NULL is because you are concatenating a NULL value which is the @variable1 contents. I believe you wanted to write down the text '@variable1' as literal:



    DECLARE @variable1 INT

    DECLARE @SQL VARCHAR(MAX)

    SET @SQL = '
    DECLARE @variable2 INT

    SET @variable2 = 1
    SET @variable1 = @variable2

    SELECT @variable1 as V1, @variable2 as V2
    '

    PRINT(@SQL)


enter image description here



  • Whenever you use EXEC, the scope changes and variables declared outside can't be accessed anymore. So inside the dynamic SQL, you won't be able to read @variable1 since it's not declare anywhere. If we execute the dynamic SQL:

enter image description here




The way you can set variables values inside a dynamic execution and be able to read them from the outside is by supplying parameters via the OUTPUT option. This will require to use the SP sp_executesql rathen than a direct EXEC:



DECLARE @externalVariable INT

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = '
DECLARE @variable2 INT = 1
SET @resultVariable = @variable2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'@resultVariable INT OUTPUT', -- Declare the "input" parameters for the dynamic SQL
@resultVariable = @externalVariable OUTPUT -- Supply the "input" parameters for the dynamic SQL

SELECT
Result = @externalVariable -- Read the updated value


Note that I changed data types to NVARCHAR since sp_executesql works with unicode inputs.



Another example with more parameters:



DECLARE @firstNumber INT = 15
DECLARE @secondNumber INT = 3
DECLARE @result INT

DECLARE @SQL NVARCHAR(MAX) = '
SET @multiplicationResult = @inputFactor1 * @inputFactor2'

EXEC sp_executesql
@stmt = @SQL,
@params = N'
@multiplicationResult INT OUTPUT,
@inputFactor1 INT,
@inputFactor2 INT',
@multiplicationResult = @result OUTPUT,
@inputFactor1 = @firstNumber,
@inputFactor2 = @secondNumber

SELECT
Result = @result -- 45!


If you don't have to read back results from variables, you can build your dynamic SQL by "hard-coding" the variables values directly into the script. Make sure to correctly use data type conversions inside the script and also escape NULL and literal values:



DECLARE @DateVariable DATETIME = GETDATE()
DECLARE @StringVariable VARCHAR(100) = NULL
DECLARE @FloatVariable FLOAT = 15.14

DECLARE @DynamicSQL VARCHAR(MAX) = '
SELECT
DateVariableContents = CONVERT(DATETIME, ''' + ISNULL(CONVERT(VARCHAR(100), @DateVariable), '') + '''),
StringVariableContents = ' + ISNULL('''' + @StringVariable + '''', '''''') + ',
FloatVariableContents = CONVERT(FLOAT, ''' + ISNULL(CONVERT(VARCHAR(100), @FloatVariable), '') + ''') '

PRINT(@DynamicSQL)

EXEC(@DynamicSQL)


Printed:



SELECT
DateVariableContents = CONVERT(DATETIME, 'Mar 21 2019 3:27PM'),
StringVariableContents = '',
FloatVariableContents = CONVERT(FLOAT, '15.124')


Result:



DateVariableContents StringVariableContents FloatVariableContents
2019-03-21 15:28:00.000 15.124






share|improve this answer














share|improve this answer



share|improve this answer








edited 10 hours ago

























answered 11 hours ago









EzLoEzLo

2,6641521




2,6641521












  • thanks a lot for your answer ! i will check it out and come back to you !

    – Matthieu RGX
    10 hours ago

















  • thanks a lot for your answer ! i will check it out and come back to you !

    – Matthieu RGX
    10 hours ago
















thanks a lot for your answer ! i will check it out and come back to you !

– Matthieu RGX
10 hours ago





thanks a lot for your answer ! i will check it out and come back to you !

– Matthieu RGX
10 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Database Administrators Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f232722%2fset-in-dynamic-query-value-of-variable-declared-outside-dynamic-query%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Reverse int within the 32-bit signed integer range: [−2^31, 2^31 − 1]Combining two 32-bit integers into one 64-bit integerDetermine if an int is within rangeLossy packing 32 bit integer to 16 bitComputing the square root of a 64-bit integerKeeping integer addition within boundsSafe multiplication of two 64-bit signed integersLeetcode 10: Regular Expression MatchingSigned integer-to-ascii x86_64 assembler macroReverse the digits of an Integer“Add two numbers given in reverse order from a linked list”

Category:Fedor von Bock Media in category "Fedor von Bock"Navigation menuUpload mediaISNI: 0000 0000 5511 3417VIAF ID: 24712551GND ID: 119294796Library of Congress authority ID: n96068363BnF ID: 12534305fSUDOC authorities ID: 034604189Open Library ID: OL338253ANKCR AUT ID: jn19990000869National Library of Israel ID: 000514068National Thesaurus for Author Names ID: 341574317ReasonatorScholiaStatistics

Kiel Indholdsfortegnelse Historie | Transport og færgeforbindelser | Sejlsport og anden sport | Kultur | Kendte personer fra Kiel | Noter | Litteratur | Eksterne henvisninger | Navigationsmenuwww.kiel.de54°19′31″N 10°8′26″Ø / 54.32528°N 10.14056°Ø / 54.32528; 10.14056Oberbürgermeister Dr. Ulf Kämpferwww.statistik-nord.deDen danske Stats StatistikKiels hjemmesiderrrWorldCat312794080n790547494030481-4