Set in dynamic query value of variable declared outside dynamic query The Next CEO of Stack OverflowScript 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 do I construct this japanese bowl?

What can we do to stop prior company from asking us questions?

How to count occurrences of text in a file?

Anatomically Correct Strange Women In Ponds Distributing Swords

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Term for the "extreme-extension" version of a straw man fallacy?

% symbol leads to superlong (forever?) compilations

What is the difference between "behavior" and "behaviour"?

Where to find order of arguments for default functions

When did Lisp start using symbols for arithmetic?

How should I support this large drywall patch?

How long to clear the 'suck zone' of a turbofan after start is initiated?

When airplanes disconnect from a tanker during air to air refueling, why do they bank so sharply to the right?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

WOW air has ceased operation, can I get my tickets refunded?

Why do remote companies require working in the US?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

Natural language into sentence logic

How to get regions to plot as graphics

Too much space between section and text in a twocolumn document

Why does standard notation not preserve intervals (visually)

How can I quit an app using Terminal?

Opposite of a diet

Inappropriate reference requests from Journal reviewers



Set in dynamic query value of variable declared outside dynamic query



The Next CEO of Stack OverflowScript 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










2















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
    Mar 21 at 13:38












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

    – Matthieu RGX
    Mar 21 at 13:39











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

    – Sabin Bio
    Mar 21 at 13:40












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

    – Matthieu RGX
    Mar 21 at 13:43






  • 1





    i've edit my question !

    – Matthieu RGX
    Mar 21 at 13:53















2















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
    Mar 21 at 13:38












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

    – Matthieu RGX
    Mar 21 at 13:39











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

    – Sabin Bio
    Mar 21 at 13:40












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

    – Matthieu RGX
    Mar 21 at 13:43






  • 1





    i've edit my question !

    – Matthieu RGX
    Mar 21 at 13:53













2












2








2








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 Mar 21 at 13:54







Matthieu RGX

















asked Mar 21 at 13:32









Matthieu RGXMatthieu RGX

297




297







  • 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
    Mar 21 at 13:38












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

    – Matthieu RGX
    Mar 21 at 13:39











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

    – Sabin Bio
    Mar 21 at 13:40












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

    – Matthieu RGX
    Mar 21 at 13:43






  • 1





    i've edit my question !

    – Matthieu RGX
    Mar 21 at 13:53












  • 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
    Mar 21 at 13:38












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

    – Matthieu RGX
    Mar 21 at 13:39











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

    – Sabin Bio
    Mar 21 at 13:40












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

    – Matthieu RGX
    Mar 21 at 13:43






  • 1





    i've edit my question !

    – Matthieu RGX
    Mar 21 at 13:53







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
Mar 21 at 13:38






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
Mar 21 at 13:38














ok but is there a way to go over that ?

– Matthieu RGX
Mar 21 at 13:39





ok but is there a way to go over that ?

– Matthieu RGX
Mar 21 at 13:39













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

– Sabin Bio
Mar 21 at 13:40






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

– Sabin Bio
Mar 21 at 13:40














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

– Matthieu RGX
Mar 21 at 13:43





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

– Matthieu RGX
Mar 21 at 13:43




1




1





i've edit my question !

– Matthieu RGX
Mar 21 at 13:53





i've edit my question !

– Matthieu RGX
Mar 21 at 13:53










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
    Mar 21 at 14:06











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
    Mar 21 at 14:06















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
    Mar 21 at 14:06













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 Mar 21 at 14:28

























answered Mar 21 at 14:03









EzLoEzLo

2,7221621




2,7221621












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

    – Matthieu RGX
    Mar 21 at 14:06

















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

    – Matthieu RGX
    Mar 21 at 14:06
















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

– Matthieu RGX
Mar 21 at 14:06





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

– Matthieu RGX
Mar 21 at 14:06

















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

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript