Is it possible for SQL statements to execute concurrently within a single session in SQL Server?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







16















I have written a stored procedure which makes use of a temporary table. I know that in SQL Server, temporary tables are session-scoped. However, I have not been able to find definitive information on exactly what a session is capable of. In particular, if it is possible for this stored procedure to execute twice concurrently in a single session, a significantly higher isolation level is required for a transaction within that procedure due to the two executions now sharing a temporary table.










share|improve this question





























    16















    I have written a stored procedure which makes use of a temporary table. I know that in SQL Server, temporary tables are session-scoped. However, I have not been able to find definitive information on exactly what a session is capable of. In particular, if it is possible for this stored procedure to execute twice concurrently in a single session, a significantly higher isolation level is required for a transaction within that procedure due to the two executions now sharing a temporary table.










    share|improve this question

























      16












      16








      16


      1






      I have written a stored procedure which makes use of a temporary table. I know that in SQL Server, temporary tables are session-scoped. However, I have not been able to find definitive information on exactly what a session is capable of. In particular, if it is possible for this stored procedure to execute twice concurrently in a single session, a significantly higher isolation level is required for a transaction within that procedure due to the two executions now sharing a temporary table.










      share|improve this question














      I have written a stored procedure which makes use of a temporary table. I know that in SQL Server, temporary tables are session-scoped. However, I have not been able to find definitive information on exactly what a session is capable of. In particular, if it is possible for this stored procedure to execute twice concurrently in a single session, a significantly higher isolation level is required for a transaction within that procedure due to the two executions now sharing a temporary table.







      sql-server sql-server-2012






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 18 at 17:37









      Trevor GiddingsTrevor Giddings

      907




      907






















          2 Answers
          2






          active

          oldest

          votes


















          19














          While Brent's answer is correct for for all practical purposes, and this is not something I've ever seen someone worry about, it is possible for multiple invocations of a stored procedure in a session to affect each other through a session-scoped #temp table.



          The good news is it's extremely unlikely to happen in the wild because



          1) #Temp tables declared inside a stored procedures or nested batches don't actually have session visibility (or lifetime). And these are by far the most common case.



          2) It requires MultipleActiveResultsets and either some very strange async client programming, or for the stored procedure to return a resultset in the middle, and the client to call another instance of the stored procedure while processing the results from the first.



          Here's a contrived example:



          using System;
          using System.Data.SqlClient;

          namespace ado.nettest
          {
          class Program
          {
          static void Main(string args)
          {
          using (var con = new SqlConnection("Server=localhost;database=tempdb;integrated security=true;MultipleActiveResultSets = True"))
          {
          con.Open();

          var procDdl = @"
          create table #t(id int)
          exec ('
          create procedure #foo
          as
          begin
          insert into #t(id) values (1);
          select top 10000 * from sys.messages m, sys.messages m2;
          select count(*) rc from #t;
          delete from #t;
          end
          ');
          ";
          var cmdDDL = con.CreateCommand();
          cmdDDL.CommandText = procDdl;
          cmdDDL.ExecuteNonQuery();

          var cmd = con.CreateCommand();
          cmd.CommandText = "exec #foo";
          using (var rdr = cmd.ExecuteReader())
          {
          rdr.Read();

          var cmd2 = con.CreateCommand();
          cmd2.CommandText = "exec #foo";
          using (var rdr2 = cmd2.ExecuteReader())
          {

          }

          while (rdr.Read())
          {

          }
          rdr.NextResult();
          rdr.Read();
          var rc = rdr.GetInt32(0);
          Console.WriteLine($"Numer of rows in temp table {rc}");

          }


          }

          Console.WriteLine("Hit any key to exit");
          Console.ReadKey();
          }
          }
          }


          which outputs



          Numer of rows in temp table 0
          Hit any key to exit


          because the second invocation of the stored procedure inserted a row, and then deleted all the rows from #t while the first invocation was waiting for the client to fetch the rows from its first resultset. Note that if the first resultset was small, the rows might get buffered and execution could continue without sending anything to the client.



          If you move the



          create table #t(id int)


          into the stored procedure it outputs:



          Numer of rows in temp table 1
          Hit any key to exit


          And with the temp table declared inside the procedure, if you change the second query to



          cmd2.CommandText = "select * from #t";


          It fails with:




          'Invalid object name '#t'.'




          Because a #temp table created inside a stored procedure or nested batch is only visible in that stored procedure or batch and in nested procedures and batches that it calls, and is destroyed when the procedure or batch ends.






          share|improve this answer





















          • 2





            As soon as I saw the question title I knew the answer was MARS.

            – Joshua
            Apr 18 at 22:21






          • 1





            "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

            – jpmc26
            Apr 20 at 13:29













          • Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

            – David Browne - Microsoft
            Apr 20 at 13:57



















          12














          Not concurrently. Your options include:




          • Run the queries one after another in the same session

          • Switch from a temp table to a global temp table (use ##TableName instead of #TableName), but be aware that the global temp table is automatically dropped when the session that created the temp table closes, and there are no other active sessions with a reference to it

          • Switch to a real user table in TempDB - you can create tables there, but be aware that they'll disappear on server restart

          • Switch to a real user table in a user database






          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%2f235197%2fis-it-possible-for-sql-statements-to-execute-concurrently-within-a-single-sessio%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            19














            While Brent's answer is correct for for all practical purposes, and this is not something I've ever seen someone worry about, it is possible for multiple invocations of a stored procedure in a session to affect each other through a session-scoped #temp table.



            The good news is it's extremely unlikely to happen in the wild because



            1) #Temp tables declared inside a stored procedures or nested batches don't actually have session visibility (or lifetime). And these are by far the most common case.



            2) It requires MultipleActiveResultsets and either some very strange async client programming, or for the stored procedure to return a resultset in the middle, and the client to call another instance of the stored procedure while processing the results from the first.



            Here's a contrived example:



            using System;
            using System.Data.SqlClient;

            namespace ado.nettest
            {
            class Program
            {
            static void Main(string args)
            {
            using (var con = new SqlConnection("Server=localhost;database=tempdb;integrated security=true;MultipleActiveResultSets = True"))
            {
            con.Open();

            var procDdl = @"
            create table #t(id int)
            exec ('
            create procedure #foo
            as
            begin
            insert into #t(id) values (1);
            select top 10000 * from sys.messages m, sys.messages m2;
            select count(*) rc from #t;
            delete from #t;
            end
            ');
            ";
            var cmdDDL = con.CreateCommand();
            cmdDDL.CommandText = procDdl;
            cmdDDL.ExecuteNonQuery();

            var cmd = con.CreateCommand();
            cmd.CommandText = "exec #foo";
            using (var rdr = cmd.ExecuteReader())
            {
            rdr.Read();

            var cmd2 = con.CreateCommand();
            cmd2.CommandText = "exec #foo";
            using (var rdr2 = cmd2.ExecuteReader())
            {

            }

            while (rdr.Read())
            {

            }
            rdr.NextResult();
            rdr.Read();
            var rc = rdr.GetInt32(0);
            Console.WriteLine($"Numer of rows in temp table {rc}");

            }


            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
            }
            }
            }


            which outputs



            Numer of rows in temp table 0
            Hit any key to exit


            because the second invocation of the stored procedure inserted a row, and then deleted all the rows from #t while the first invocation was waiting for the client to fetch the rows from its first resultset. Note that if the first resultset was small, the rows might get buffered and execution could continue without sending anything to the client.



            If you move the



            create table #t(id int)


            into the stored procedure it outputs:



            Numer of rows in temp table 1
            Hit any key to exit


            And with the temp table declared inside the procedure, if you change the second query to



            cmd2.CommandText = "select * from #t";


            It fails with:




            'Invalid object name '#t'.'




            Because a #temp table created inside a stored procedure or nested batch is only visible in that stored procedure or batch and in nested procedures and batches that it calls, and is destroyed when the procedure or batch ends.






            share|improve this answer





















            • 2





              As soon as I saw the question title I knew the answer was MARS.

              – Joshua
              Apr 18 at 22:21






            • 1





              "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

              – jpmc26
              Apr 20 at 13:29













            • Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

              – David Browne - Microsoft
              Apr 20 at 13:57
















            19














            While Brent's answer is correct for for all practical purposes, and this is not something I've ever seen someone worry about, it is possible for multiple invocations of a stored procedure in a session to affect each other through a session-scoped #temp table.



            The good news is it's extremely unlikely to happen in the wild because



            1) #Temp tables declared inside a stored procedures or nested batches don't actually have session visibility (or lifetime). And these are by far the most common case.



            2) It requires MultipleActiveResultsets and either some very strange async client programming, or for the stored procedure to return a resultset in the middle, and the client to call another instance of the stored procedure while processing the results from the first.



            Here's a contrived example:



            using System;
            using System.Data.SqlClient;

            namespace ado.nettest
            {
            class Program
            {
            static void Main(string args)
            {
            using (var con = new SqlConnection("Server=localhost;database=tempdb;integrated security=true;MultipleActiveResultSets = True"))
            {
            con.Open();

            var procDdl = @"
            create table #t(id int)
            exec ('
            create procedure #foo
            as
            begin
            insert into #t(id) values (1);
            select top 10000 * from sys.messages m, sys.messages m2;
            select count(*) rc from #t;
            delete from #t;
            end
            ');
            ";
            var cmdDDL = con.CreateCommand();
            cmdDDL.CommandText = procDdl;
            cmdDDL.ExecuteNonQuery();

            var cmd = con.CreateCommand();
            cmd.CommandText = "exec #foo";
            using (var rdr = cmd.ExecuteReader())
            {
            rdr.Read();

            var cmd2 = con.CreateCommand();
            cmd2.CommandText = "exec #foo";
            using (var rdr2 = cmd2.ExecuteReader())
            {

            }

            while (rdr.Read())
            {

            }
            rdr.NextResult();
            rdr.Read();
            var rc = rdr.GetInt32(0);
            Console.WriteLine($"Numer of rows in temp table {rc}");

            }


            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
            }
            }
            }


            which outputs



            Numer of rows in temp table 0
            Hit any key to exit


            because the second invocation of the stored procedure inserted a row, and then deleted all the rows from #t while the first invocation was waiting for the client to fetch the rows from its first resultset. Note that if the first resultset was small, the rows might get buffered and execution could continue without sending anything to the client.



            If you move the



            create table #t(id int)


            into the stored procedure it outputs:



            Numer of rows in temp table 1
            Hit any key to exit


            And with the temp table declared inside the procedure, if you change the second query to



            cmd2.CommandText = "select * from #t";


            It fails with:




            'Invalid object name '#t'.'




            Because a #temp table created inside a stored procedure or nested batch is only visible in that stored procedure or batch and in nested procedures and batches that it calls, and is destroyed when the procedure or batch ends.






            share|improve this answer





















            • 2





              As soon as I saw the question title I knew the answer was MARS.

              – Joshua
              Apr 18 at 22:21






            • 1





              "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

              – jpmc26
              Apr 20 at 13:29













            • Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

              – David Browne - Microsoft
              Apr 20 at 13:57














            19












            19








            19







            While Brent's answer is correct for for all practical purposes, and this is not something I've ever seen someone worry about, it is possible for multiple invocations of a stored procedure in a session to affect each other through a session-scoped #temp table.



            The good news is it's extremely unlikely to happen in the wild because



            1) #Temp tables declared inside a stored procedures or nested batches don't actually have session visibility (or lifetime). And these are by far the most common case.



            2) It requires MultipleActiveResultsets and either some very strange async client programming, or for the stored procedure to return a resultset in the middle, and the client to call another instance of the stored procedure while processing the results from the first.



            Here's a contrived example:



            using System;
            using System.Data.SqlClient;

            namespace ado.nettest
            {
            class Program
            {
            static void Main(string args)
            {
            using (var con = new SqlConnection("Server=localhost;database=tempdb;integrated security=true;MultipleActiveResultSets = True"))
            {
            con.Open();

            var procDdl = @"
            create table #t(id int)
            exec ('
            create procedure #foo
            as
            begin
            insert into #t(id) values (1);
            select top 10000 * from sys.messages m, sys.messages m2;
            select count(*) rc from #t;
            delete from #t;
            end
            ');
            ";
            var cmdDDL = con.CreateCommand();
            cmdDDL.CommandText = procDdl;
            cmdDDL.ExecuteNonQuery();

            var cmd = con.CreateCommand();
            cmd.CommandText = "exec #foo";
            using (var rdr = cmd.ExecuteReader())
            {
            rdr.Read();

            var cmd2 = con.CreateCommand();
            cmd2.CommandText = "exec #foo";
            using (var rdr2 = cmd2.ExecuteReader())
            {

            }

            while (rdr.Read())
            {

            }
            rdr.NextResult();
            rdr.Read();
            var rc = rdr.GetInt32(0);
            Console.WriteLine($"Numer of rows in temp table {rc}");

            }


            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
            }
            }
            }


            which outputs



            Numer of rows in temp table 0
            Hit any key to exit


            because the second invocation of the stored procedure inserted a row, and then deleted all the rows from #t while the first invocation was waiting for the client to fetch the rows from its first resultset. Note that if the first resultset was small, the rows might get buffered and execution could continue without sending anything to the client.



            If you move the



            create table #t(id int)


            into the stored procedure it outputs:



            Numer of rows in temp table 1
            Hit any key to exit


            And with the temp table declared inside the procedure, if you change the second query to



            cmd2.CommandText = "select * from #t";


            It fails with:




            'Invalid object name '#t'.'




            Because a #temp table created inside a stored procedure or nested batch is only visible in that stored procedure or batch and in nested procedures and batches that it calls, and is destroyed when the procedure or batch ends.






            share|improve this answer















            While Brent's answer is correct for for all practical purposes, and this is not something I've ever seen someone worry about, it is possible for multiple invocations of a stored procedure in a session to affect each other through a session-scoped #temp table.



            The good news is it's extremely unlikely to happen in the wild because



            1) #Temp tables declared inside a stored procedures or nested batches don't actually have session visibility (or lifetime). And these are by far the most common case.



            2) It requires MultipleActiveResultsets and either some very strange async client programming, or for the stored procedure to return a resultset in the middle, and the client to call another instance of the stored procedure while processing the results from the first.



            Here's a contrived example:



            using System;
            using System.Data.SqlClient;

            namespace ado.nettest
            {
            class Program
            {
            static void Main(string args)
            {
            using (var con = new SqlConnection("Server=localhost;database=tempdb;integrated security=true;MultipleActiveResultSets = True"))
            {
            con.Open();

            var procDdl = @"
            create table #t(id int)
            exec ('
            create procedure #foo
            as
            begin
            insert into #t(id) values (1);
            select top 10000 * from sys.messages m, sys.messages m2;
            select count(*) rc from #t;
            delete from #t;
            end
            ');
            ";
            var cmdDDL = con.CreateCommand();
            cmdDDL.CommandText = procDdl;
            cmdDDL.ExecuteNonQuery();

            var cmd = con.CreateCommand();
            cmd.CommandText = "exec #foo";
            using (var rdr = cmd.ExecuteReader())
            {
            rdr.Read();

            var cmd2 = con.CreateCommand();
            cmd2.CommandText = "exec #foo";
            using (var rdr2 = cmd2.ExecuteReader())
            {

            }

            while (rdr.Read())
            {

            }
            rdr.NextResult();
            rdr.Read();
            var rc = rdr.GetInt32(0);
            Console.WriteLine($"Numer of rows in temp table {rc}");

            }


            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
            }
            }
            }


            which outputs



            Numer of rows in temp table 0
            Hit any key to exit


            because the second invocation of the stored procedure inserted a row, and then deleted all the rows from #t while the first invocation was waiting for the client to fetch the rows from its first resultset. Note that if the first resultset was small, the rows might get buffered and execution could continue without sending anything to the client.



            If you move the



            create table #t(id int)


            into the stored procedure it outputs:



            Numer of rows in temp table 1
            Hit any key to exit


            And with the temp table declared inside the procedure, if you change the second query to



            cmd2.CommandText = "select * from #t";


            It fails with:




            'Invalid object name '#t'.'




            Because a #temp table created inside a stored procedure or nested batch is only visible in that stored procedure or batch and in nested procedures and batches that it calls, and is destroyed when the procedure or batch ends.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 23 at 19:20

























            answered Apr 18 at 22:02









            David Browne - MicrosoftDavid Browne - Microsoft

            13.3k936




            13.3k936








            • 2





              As soon as I saw the question title I knew the answer was MARS.

              – Joshua
              Apr 18 at 22:21






            • 1





              "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

              – jpmc26
              Apr 20 at 13:29













            • Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

              – David Browne - Microsoft
              Apr 20 at 13:57














            • 2





              As soon as I saw the question title I knew the answer was MARS.

              – Joshua
              Apr 18 at 22:21






            • 1





              "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

              – jpmc26
              Apr 20 at 13:29













            • Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

              – David Browne - Microsoft
              Apr 20 at 13:57








            2




            2





            As soon as I saw the question title I knew the answer was MARS.

            – Joshua
            Apr 18 at 22:21





            As soon as I saw the question title I knew the answer was MARS.

            – Joshua
            Apr 18 at 22:21




            1




            1





            "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

            – jpmc26
            Apr 20 at 13:29







            "some very strange async client programming" Given the introduction of built in asych features to C#, are you certain that multiple queries running asynchronous won't become more common?

            – jpmc26
            Apr 20 at 13:29















            Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

            – David Browne - Microsoft
            Apr 20 at 13:57





            Sure but usually the SqlConnection is not reused while the client is waiting for the command. That’s what would be strange.

            – David Browne - Microsoft
            Apr 20 at 13:57













            12














            Not concurrently. Your options include:




            • Run the queries one after another in the same session

            • Switch from a temp table to a global temp table (use ##TableName instead of #TableName), but be aware that the global temp table is automatically dropped when the session that created the temp table closes, and there are no other active sessions with a reference to it

            • Switch to a real user table in TempDB - you can create tables there, but be aware that they'll disappear on server restart

            • Switch to a real user table in a user database






            share|improve this answer




























              12














              Not concurrently. Your options include:




              • Run the queries one after another in the same session

              • Switch from a temp table to a global temp table (use ##TableName instead of #TableName), but be aware that the global temp table is automatically dropped when the session that created the temp table closes, and there are no other active sessions with a reference to it

              • Switch to a real user table in TempDB - you can create tables there, but be aware that they'll disappear on server restart

              • Switch to a real user table in a user database






              share|improve this answer


























                12












                12








                12







                Not concurrently. Your options include:




                • Run the queries one after another in the same session

                • Switch from a temp table to a global temp table (use ##TableName instead of #TableName), but be aware that the global temp table is automatically dropped when the session that created the temp table closes, and there are no other active sessions with a reference to it

                • Switch to a real user table in TempDB - you can create tables there, but be aware that they'll disappear on server restart

                • Switch to a real user table in a user database






                share|improve this answer













                Not concurrently. Your options include:




                • Run the queries one after another in the same session

                • Switch from a temp table to a global temp table (use ##TableName instead of #TableName), but be aware that the global temp table is automatically dropped when the session that created the temp table closes, and there are no other active sessions with a reference to it

                • Switch to a real user table in TempDB - you can create tables there, but be aware that they'll disappear on server restart

                • Switch to a real user table in a user database







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 18 at 17:41









                Brent OzarBrent Ozar

                36.2k19113249




                36.2k19113249






























                    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%2f235197%2fis-it-possible-for-sql-statements-to-execute-concurrently-within-a-single-sessio%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

                    He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

                    Bunad

                    Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum