SQL PRINT vs SQL EXEC The Next CEO of Stack Overflowsp_ExecuteSQL, performance and table variablesDoes Detach/Attach or Offline/Online Clear the Buffer Cache for a Particular Database?Buffer Size Changing?Safe alternative to exec(sql)SQL Trigger QuestionWhy high compile times for functions with XML on SQL Server 2016?SQL PRINT statement prints nothingAll Queries are slow on Prod than Dev ServerSQL Server Patch Level Is Inaccurate, Causing Upgrade IssuesDBCC ShrinkFile not working

Why the difference in type-inference over the as-pattern in two similar function definitions?

Where do students learn to solve polynomial equations these days?

Is a distribution that is normal, but highly skewed considered Gaussian?

How did people program for Consoles with multiple CPUs?

Is French Guiana a (hard) EU border?

"misplaced omit" error when >centering columns

What was the first Unix version to run on a microcomputer?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Dominated convergence theorem - what sequence?

What steps are necessary to read a Modern SSD in Medieval Europe?

Proper way to express "He disappeared them"

What happened in Rome, when the western empire "fell"?

Why do airplanes bank sharply to the right after air-to-air refueling?

How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2?

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Can a Bladesinger Wizard use Bladesong with a Hand Crossbow?

Flying from Cape Town to England and return to another province

What is the value of α and β in a triangle?

INSERT to a table from a database to other (same SQL Server) using Dynamic SQL

Can we say or write : "No, it'sn't"?

Can you be charged for obstruction for refusing to answer questions?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Reference request: Grassmannian and Plucker coordinates in type B, C, D

Method for adding error messages to a dictionary given a key



SQL PRINT vs SQL EXEC



The Next CEO of Stack Overflowsp_ExecuteSQL, performance and table variablesDoes Detach/Attach or Offline/Online Clear the Buffer Cache for a Particular Database?Buffer Size Changing?Safe alternative to exec(sql)SQL Trigger QuestionWhy high compile times for functions with XML on SQL Server 2016?SQL PRINT statement prints nothingAll Queries are slow on Prod than Dev ServerSQL Server Patch Level Is Inaccurate, Causing Upgrade IssuesDBCC ShrinkFile not working










0















When executing the query below, if I use PRINT it prints correctly. I can copy and paste the printed code and execute it. However, if I use EXEC I get the following error:



error on exec



Is there a way of simplifying what I am doing? Why do SQL PRINT and SQL EXEC deliver these two very different result sets?



DECLARE @TableName as NVARCHAR(250), @SQL as VARCHAR(MAX);

DECLARE @TableCursor as CURSOR;
SET @TableCursor = CURSOR FOR
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
AND name like 'HISTORY_MasterList_%'
ORDER BY sobjects.name

OPEN @TableCursor;
FETCH NEXT FROM @TableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL ='select '''+ @TableName +''', 0
Union All
select All ''Server Count'',count(1) from ['+ @TableName +']
Union All
select All ''Server Cores'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
Union All
select ''Production Servers'',count(1) from ['+ @TableName +'] where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
Union All
select ''Production Cores'', sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
Union All
select ''Production Server Count after filtering out passive/failover servers'', count(1) from
(select distinct m.ServerName
from ['+ @TableName +'] m
inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
and unit <> 0) aa
Union All
select ''Production Server Cores after filtering out passive/failover servers'', sum(convert(decimal(18,0),cores)) from(
select distinct m.ServerName, m.Cores
from ['+ @TableName +'] m
inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
and unit <> 0) aa
Union All
select ''Non-Prod SQL Instances downgraded to Developer Edition'',count(1) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
Union All
select ''Non-Prod SQL Instance Core Count downgraded to Developer Edition'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
Union All
select ''Non-Prod VMs moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''VM Moved/right sized from Prod Env to NonProd''
Union All
select ''Non-Prod VMs TO BE moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''Sent for V2V - non prod split''
'

EXEC @SQL

FETCH NEXT FROM @TableCursor INTO @TableName;
END
CLOSE @TableCursor;
DEALLOCATE @TableCursor;









share|improve this question




























    0















    When executing the query below, if I use PRINT it prints correctly. I can copy and paste the printed code and execute it. However, if I use EXEC I get the following error:



    error on exec



    Is there a way of simplifying what I am doing? Why do SQL PRINT and SQL EXEC deliver these two very different result sets?



    DECLARE @TableName as NVARCHAR(250), @SQL as VARCHAR(MAX);

    DECLARE @TableCursor as CURSOR;
    SET @TableCursor = CURSOR FOR
    SELECT sobjects.name
    FROM sysobjects sobjects
    WHERE sobjects.xtype = 'U'
    AND name like 'HISTORY_MasterList_%'
    ORDER BY sobjects.name

    OPEN @TableCursor;
    FETCH NEXT FROM @TableCursor INTO @TableName;
    WHILE @@FETCH_STATUS = 0
    BEGIN
    SET @SQL ='select '''+ @TableName +''', 0
    Union All
    select All ''Server Count'',count(1) from ['+ @TableName +']
    Union All
    select All ''Server Cores'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
    Union All
    select ''Production Servers'',count(1) from ['+ @TableName +'] where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
    Union All
    select ''Production Cores'', sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
    where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
    Union All
    select ''Production Server Count after filtering out passive/failover servers'', count(1) from
    (select distinct m.ServerName
    from ['+ @TableName +'] m
    inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
    where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
    and unit <> 0) aa
    Union All
    select ''Production Server Cores after filtering out passive/failover servers'', sum(convert(decimal(18,0),cores)) from(
    select distinct m.ServerName, m.Cores
    from ['+ @TableName +'] m
    inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
    where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
    and unit <> 0) aa
    Union All
    select ''Non-Prod SQL Instances downgraded to Developer Edition'',count(1) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
    Union All
    select ''Non-Prod SQL Instance Core Count downgraded to Developer Edition'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
    Union All
    select ''Non-Prod VMs moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''VM Moved/right sized from Prod Env to NonProd''
    Union All
    select ''Non-Prod VMs TO BE moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''Sent for V2V - non prod split''
    '

    EXEC @SQL

    FETCH NEXT FROM @TableCursor INTO @TableName;
    END
    CLOSE @TableCursor;
    DEALLOCATE @TableCursor;









    share|improve this question


























      0












      0








      0








      When executing the query below, if I use PRINT it prints correctly. I can copy and paste the printed code and execute it. However, if I use EXEC I get the following error:



      error on exec



      Is there a way of simplifying what I am doing? Why do SQL PRINT and SQL EXEC deliver these two very different result sets?



      DECLARE @TableName as NVARCHAR(250), @SQL as VARCHAR(MAX);

      DECLARE @TableCursor as CURSOR;
      SET @TableCursor = CURSOR FOR
      SELECT sobjects.name
      FROM sysobjects sobjects
      WHERE sobjects.xtype = 'U'
      AND name like 'HISTORY_MasterList_%'
      ORDER BY sobjects.name

      OPEN @TableCursor;
      FETCH NEXT FROM @TableCursor INTO @TableName;
      WHILE @@FETCH_STATUS = 0
      BEGIN
      SET @SQL ='select '''+ @TableName +''', 0
      Union All
      select All ''Server Count'',count(1) from ['+ @TableName +']
      Union All
      select All ''Server Cores'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
      Union All
      select ''Production Servers'',count(1) from ['+ @TableName +'] where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      Union All
      select ''Production Cores'', sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
      where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      Union All
      select ''Production Server Count after filtering out passive/failover servers'', count(1) from
      (select distinct m.ServerName
      from ['+ @TableName +'] m
      inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
      where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      and unit <> 0) aa
      Union All
      select ''Production Server Cores after filtering out passive/failover servers'', sum(convert(decimal(18,0),cores)) from(
      select distinct m.ServerName, m.Cores
      from ['+ @TableName +'] m
      inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
      where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      and unit <> 0) aa
      Union All
      select ''Non-Prod SQL Instances downgraded to Developer Edition'',count(1) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
      Union All
      select ''Non-Prod SQL Instance Core Count downgraded to Developer Edition'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
      Union All
      select ''Non-Prod VMs moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''VM Moved/right sized from Prod Env to NonProd''
      Union All
      select ''Non-Prod VMs TO BE moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''Sent for V2V - non prod split''
      '

      EXEC @SQL

      FETCH NEXT FROM @TableCursor INTO @TableName;
      END
      CLOSE @TableCursor;
      DEALLOCATE @TableCursor;









      share|improve this question
















      When executing the query below, if I use PRINT it prints correctly. I can copy and paste the printed code and execute it. However, if I use EXEC I get the following error:



      error on exec



      Is there a way of simplifying what I am doing? Why do SQL PRINT and SQL EXEC deliver these two very different result sets?



      DECLARE @TableName as NVARCHAR(250), @SQL as VARCHAR(MAX);

      DECLARE @TableCursor as CURSOR;
      SET @TableCursor = CURSOR FOR
      SELECT sobjects.name
      FROM sysobjects sobjects
      WHERE sobjects.xtype = 'U'
      AND name like 'HISTORY_MasterList_%'
      ORDER BY sobjects.name

      OPEN @TableCursor;
      FETCH NEXT FROM @TableCursor INTO @TableName;
      WHILE @@FETCH_STATUS = 0
      BEGIN
      SET @SQL ='select '''+ @TableName +''', 0
      Union All
      select All ''Server Count'',count(1) from ['+ @TableName +']
      Union All
      select All ''Server Cores'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
      Union All
      select ''Production Servers'',count(1) from ['+ @TableName +'] where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      Union All
      select ''Production Cores'', sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
      where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      Union All
      select ''Production Server Count after filtering out passive/failover servers'', count(1) from
      (select distinct m.ServerName
      from ['+ @TableName +'] m
      inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
      where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      and unit <> 0) aa
      Union All
      select ''Production Server Cores after filtering out passive/failover servers'', sum(convert(decimal(18,0),cores)) from(
      select distinct m.ServerName, m.Cores
      from ['+ @TableName +'] m
      inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
      where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
      and unit <> 0) aa
      Union All
      select ''Non-Prod SQL Instances downgraded to Developer Edition'',count(1) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
      Union All
      select ''Non-Prod SQL Instance Core Count downgraded to Developer Edition'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
      Union All
      select ''Non-Prod VMs moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''VM Moved/right sized from Prod Env to NonProd''
      Union All
      select ''Non-Prod VMs TO BE moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''Sent for V2V - non prod split''
      '

      EXEC @SQL

      FETCH NEXT FROM @TableCursor INTO @TableName;
      END
      CLOSE @TableCursor;
      DEALLOCATE @TableCursor;






      sql-server sql-server-2012 sql-server-2008 sql-server-2008-r2 t-sql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 19 at 11:33









      Glorfindel

      1,0231816




      1,0231816










      asked Mar 19 at 6:15









      VorsterVorster

      12910




      12910




















          1 Answer
          1






          active

          oldest

          votes


















          5














          The error is saying that ...it is not a valid identifier.
          When you pass EXEC @SQL , it is expecting that @sql to represent the name of a stored procedure (or scalar function). Hence the error message: ...it is not a valid identifier.



          If you want to execute a text, to pass dynamically , you should encapsulate that text inside ( ), like EXEC (@SQL).






          share|improve this answer























            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%2f232492%2fsql-print-vs-sql-exec%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














            The error is saying that ...it is not a valid identifier.
            When you pass EXEC @SQL , it is expecting that @sql to represent the name of a stored procedure (or scalar function). Hence the error message: ...it is not a valid identifier.



            If you want to execute a text, to pass dynamically , you should encapsulate that text inside ( ), like EXEC (@SQL).






            share|improve this answer



























              5














              The error is saying that ...it is not a valid identifier.
              When you pass EXEC @SQL , it is expecting that @sql to represent the name of a stored procedure (or scalar function). Hence the error message: ...it is not a valid identifier.



              If you want to execute a text, to pass dynamically , you should encapsulate that text inside ( ), like EXEC (@SQL).






              share|improve this answer

























                5












                5








                5







                The error is saying that ...it is not a valid identifier.
                When you pass EXEC @SQL , it is expecting that @sql to represent the name of a stored procedure (or scalar function). Hence the error message: ...it is not a valid identifier.



                If you want to execute a text, to pass dynamically , you should encapsulate that text inside ( ), like EXEC (@SQL).






                share|improve this answer













                The error is saying that ...it is not a valid identifier.
                When you pass EXEC @SQL , it is expecting that @sql to represent the name of a stored procedure (or scalar function). Hence the error message: ...it is not a valid identifier.



                If you want to execute a text, to pass dynamically , you should encapsulate that text inside ( ), like EXEC (@SQL).







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 19 at 6:39









                Sabin BioSabin Bio

                2,1671819




                2,1671819



























                    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%2f232492%2fsql-print-vs-sql-exec%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

                    How should I support this large drywall patch? Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How do I cover large gaps in drywall?How do I keep drywall around a patch from crumbling?Can I glue a second layer of drywall?How to patch long strip on drywall?Large drywall patch: how to avoid bulging seams?Drywall Mesh Patch vs. Bulge? To remove or not to remove?How to fix this drywall job?Prep drywall before backsplashWhat's the best way to fix this horrible drywall patch job?Drywall patching using 3M Patch Plus Primer

                    random experiment with two different functions on unit interval Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Random variable and probability space notionsRandom Walk with EdgesFinding functions where the increase over a random interval is Poisson distributedNumber of days until dayCan an observed event in fact be of zero probability?Unit random processmodels of coins and uniform distributionHow to get the number of successes given $n$ trials , probability $P$ and a random variable $X$Absorbing Markov chain in a computer. Is “almost every” turned into always convergence in computer executions?Stopped random walk is not uniformly integrable

                    Lowndes Grove History Architecture References Navigation menu32°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661132°48′6″N 79°57′58″W / 32.80167°N 79.96611°W / 32.80167; -79.9661178002500"National Register Information System"Historic houses of South Carolina"Lowndes Grove""+32° 48' 6.00", −79° 57' 58.00""Lowndes Grove, Charleston County (260 St. Margaret St., Charleston)""Lowndes Grove"The Charleston ExpositionIt Happened in South Carolina"Lowndes Grove (House), Saint Margaret Street & Sixth Avenue, Charleston, Charleston County, SC(Photographs)"Plantations of the Carolina Low Countrye