SQL query, store result of SELECT in local variable












43















I create a query with some results reused. I search a way to put the result into a variable and use it.



A simple way to see what I want something looking like this - I want this:



DECLARE @result1 ?????

SET @result1 = SELECT a,b,c FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1


Not this :



 SELECT a AS val FROM (SELECT a,b,c FROM table1)
UNION
SELECT b AS val FROM (SELECT a,b,c FROM table1)
UNION
SELECT c AS val FROM (SELECT a,b,c FROM table1)


It's not the result of this query that I'm concerned with, but instead:




  1. to stop selecting the result so many times - in my sample, I reselected the table 3 times


  2. the query of @result1 is usually so much more complex. So, with a variable, the code will be cleaner.



Maybe I want to much - or there's a type of local variable. Or using the type table and set data inside.



What do you suggest me?



Thank you










share|improve this question





























    43















    I create a query with some results reused. I search a way to put the result into a variable and use it.



    A simple way to see what I want something looking like this - I want this:



    DECLARE @result1 ?????

    SET @result1 = SELECT a,b,c FROM table1
    SELECT a AS val FROM @result1
    UNION
    SELECT b AS val FROM @result1
    UNION
    SELECT c AS val FROM @result1


    Not this :



     SELECT a AS val FROM (SELECT a,b,c FROM table1)
    UNION
    SELECT b AS val FROM (SELECT a,b,c FROM table1)
    UNION
    SELECT c AS val FROM (SELECT a,b,c FROM table1)


    It's not the result of this query that I'm concerned with, but instead:




    1. to stop selecting the result so many times - in my sample, I reselected the table 3 times


    2. the query of @result1 is usually so much more complex. So, with a variable, the code will be cleaner.



    Maybe I want to much - or there's a type of local variable. Or using the type table and set data inside.



    What do you suggest me?



    Thank you










    share|improve this question



























      43












      43








      43


      7






      I create a query with some results reused. I search a way to put the result into a variable and use it.



      A simple way to see what I want something looking like this - I want this:



      DECLARE @result1 ?????

      SET @result1 = SELECT a,b,c FROM table1
      SELECT a AS val FROM @result1
      UNION
      SELECT b AS val FROM @result1
      UNION
      SELECT c AS val FROM @result1


      Not this :



       SELECT a AS val FROM (SELECT a,b,c FROM table1)
      UNION
      SELECT b AS val FROM (SELECT a,b,c FROM table1)
      UNION
      SELECT c AS val FROM (SELECT a,b,c FROM table1)


      It's not the result of this query that I'm concerned with, but instead:




      1. to stop selecting the result so many times - in my sample, I reselected the table 3 times


      2. the query of @result1 is usually so much more complex. So, with a variable, the code will be cleaner.



      Maybe I want to much - or there's a type of local variable. Or using the type table and set data inside.



      What do you suggest me?



      Thank you










      share|improve this question
















      I create a query with some results reused. I search a way to put the result into a variable and use it.



      A simple way to see what I want something looking like this - I want this:



      DECLARE @result1 ?????

      SET @result1 = SELECT a,b,c FROM table1
      SELECT a AS val FROM @result1
      UNION
      SELECT b AS val FROM @result1
      UNION
      SELECT c AS val FROM @result1


      Not this :



       SELECT a AS val FROM (SELECT a,b,c FROM table1)
      UNION
      SELECT b AS val FROM (SELECT a,b,c FROM table1)
      UNION
      SELECT c AS val FROM (SELECT a,b,c FROM table1)


      It's not the result of this query that I'm concerned with, but instead:




      1. to stop selecting the result so many times - in my sample, I reselected the table 3 times


      2. the query of @result1 is usually so much more complex. So, with a variable, the code will be cleaner.



      Maybe I want to much - or there's a type of local variable. Or using the type table and set data inside.



      What do you suggest me?



      Thank you







      sql-server-2005






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 27 '12 at 18:11









      marc_s

      580k13011191266




      580k13011191266










      asked Apr 27 '12 at 18:07









      forXforX

      84521942




      84521942
























          4 Answers
          4






          active

          oldest

          votes


















          48














          You can create table variables:



          DECLARE @result1 TABLE (a INT, b INT, c INT)

          INSERT INTO @result1
          SELECT a, b, c
          FROM table1

          SELECT a AS val FROM @result1
          UNION
          SELECT b AS val FROM @result1
          UNION
          SELECT c AS val FROM @result1


          This should be fine for what you need.






          share|improve this answer
























          • yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

            – forX
            Apr 27 '12 at 18:19



















          13














          Here are some other approaches you can take.



          1. CTE with union:



          ;WITH cte AS (SELECT a, b, c FROM table1)
          SELECT a AS val FROM cte
          UNION SELECT b AS val FROM cte
          UNION SELECT c AS val FROM cte;


          2. CTE with unpivot:



          ;WITH cte AS (SELECT a, b, c FROM table1)
          SELECT DISTINCT val
          FROM cte
          UNPIVOT (val FOR col IN (a, b, c)) u;





          share|improve this answer



















          • 1





            with cte seems interesting. dont need to create table of each row. tank you

            – forX
            Apr 27 '12 at 19:42











          • @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

            – javad amiry
            Sep 27 '14 at 21:51



















          1














          Isn't this a much simpler solution, if I correctly understand the question, of course.



          I want to load email addresses that are in a table called "spam" into a variable.



          select email from spam


          produces the following list, say:



          .accountant
          .bid
          .buiilldanything.com
          .club
          .cn
          .cricket
          .date
          .download
          .eu


          To load into the variable @list:



          declare @list as varchar(8000)
          set @list += @list (select email from spam)


          @list may now be INSERTed into a table, etc.



          I hope this helps.



          To use it for a .csv file or in VB, spike the code:



          declare @list as varchar(8000)
          set @list += @list (select '"'+email+',"' from spam)
          print @list


          and it produces ready-made code to use elsewhere:



          ".accountant,"
          ".bid,"
          ".buiilldanything.com,"
          ".club,"
          ".cn,"
          ".cricket,"
          ".date,"
          ".download,"
          ".eu,"


          One can be very creative.



          Thanks



          Nico






          share|improve this answer

































            0














            I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.



            declare @myVal int;
            set @myVal = isnull((select a from table1), 0);



            Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              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: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              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%2fstackoverflow.com%2fquestions%2f10355694%2fsql-query-store-result-of-select-in-local-variable%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              48














              You can create table variables:



              DECLARE @result1 TABLE (a INT, b INT, c INT)

              INSERT INTO @result1
              SELECT a, b, c
              FROM table1

              SELECT a AS val FROM @result1
              UNION
              SELECT b AS val FROM @result1
              UNION
              SELECT c AS val FROM @result1


              This should be fine for what you need.






              share|improve this answer
























              • yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

                – forX
                Apr 27 '12 at 18:19
















              48














              You can create table variables:



              DECLARE @result1 TABLE (a INT, b INT, c INT)

              INSERT INTO @result1
              SELECT a, b, c
              FROM table1

              SELECT a AS val FROM @result1
              UNION
              SELECT b AS val FROM @result1
              UNION
              SELECT c AS val FROM @result1


              This should be fine for what you need.






              share|improve this answer
























              • yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

                – forX
                Apr 27 '12 at 18:19














              48












              48








              48







              You can create table variables:



              DECLARE @result1 TABLE (a INT, b INT, c INT)

              INSERT INTO @result1
              SELECT a, b, c
              FROM table1

              SELECT a AS val FROM @result1
              UNION
              SELECT b AS val FROM @result1
              UNION
              SELECT c AS val FROM @result1


              This should be fine for what you need.






              share|improve this answer













              You can create table variables:



              DECLARE @result1 TABLE (a INT, b INT, c INT)

              INSERT INTO @result1
              SELECT a, b, c
              FROM table1

              SELECT a AS val FROM @result1
              UNION
              SELECT b AS val FROM @result1
              UNION
              SELECT c AS val FROM @result1


              This should be fine for what you need.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 27 '12 at 18:11









              Vince PergolizziVince Pergolizzi

              4,14821515




              4,14821515













              • yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

                – forX
                Apr 27 '12 at 18:19



















              • yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

                – forX
                Apr 27 '12 at 18:19

















              yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

              – forX
              Apr 27 '12 at 18:19





              yeah, that was what I think I should do. I just post it to know if theres another way. Tank you.

              – forX
              Apr 27 '12 at 18:19













              13














              Here are some other approaches you can take.



              1. CTE with union:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT a AS val FROM cte
              UNION SELECT b AS val FROM cte
              UNION SELECT c AS val FROM cte;


              2. CTE with unpivot:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT DISTINCT val
              FROM cte
              UNPIVOT (val FOR col IN (a, b, c)) u;





              share|improve this answer



















              • 1





                with cte seems interesting. dont need to create table of each row. tank you

                – forX
                Apr 27 '12 at 19:42











              • @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

                – javad amiry
                Sep 27 '14 at 21:51
















              13














              Here are some other approaches you can take.



              1. CTE with union:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT a AS val FROM cte
              UNION SELECT b AS val FROM cte
              UNION SELECT c AS val FROM cte;


              2. CTE with unpivot:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT DISTINCT val
              FROM cte
              UNPIVOT (val FOR col IN (a, b, c)) u;





              share|improve this answer



















              • 1





                with cte seems interesting. dont need to create table of each row. tank you

                – forX
                Apr 27 '12 at 19:42











              • @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

                – javad amiry
                Sep 27 '14 at 21:51














              13












              13








              13







              Here are some other approaches you can take.



              1. CTE with union:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT a AS val FROM cte
              UNION SELECT b AS val FROM cte
              UNION SELECT c AS val FROM cte;


              2. CTE with unpivot:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT DISTINCT val
              FROM cte
              UNPIVOT (val FOR col IN (a, b, c)) u;





              share|improve this answer













              Here are some other approaches you can take.



              1. CTE with union:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT a AS val FROM cte
              UNION SELECT b AS val FROM cte
              UNION SELECT c AS val FROM cte;


              2. CTE with unpivot:



              ;WITH cte AS (SELECT a, b, c FROM table1)
              SELECT DISTINCT val
              FROM cte
              UNPIVOT (val FOR col IN (a, b, c)) u;






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 27 '12 at 19:24









              Anthony FaullAnthony Faull

              13.3k53765




              13.3k53765








              • 1





                with cte seems interesting. dont need to create table of each row. tank you

                – forX
                Apr 27 '12 at 19:42











              • @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

                – javad amiry
                Sep 27 '14 at 21:51














              • 1





                with cte seems interesting. dont need to create table of each row. tank you

                – forX
                Apr 27 '12 at 19:42











              • @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

                – javad amiry
                Sep 27 '14 at 21:51








              1




              1





              with cte seems interesting. dont need to create table of each row. tank you

              – forX
              Apr 27 '12 at 19:42





              with cte seems interesting. dont need to create table of each row. tank you

              – forX
              Apr 27 '12 at 19:42













              @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

              – javad amiry
              Sep 27 '14 at 21:51





              @AnthonyFaull thanks to answer. But, how about an in(statement) statement?

              – javad amiry
              Sep 27 '14 at 21:51











              1














              Isn't this a much simpler solution, if I correctly understand the question, of course.



              I want to load email addresses that are in a table called "spam" into a variable.



              select email from spam


              produces the following list, say:



              .accountant
              .bid
              .buiilldanything.com
              .club
              .cn
              .cricket
              .date
              .download
              .eu


              To load into the variable @list:



              declare @list as varchar(8000)
              set @list += @list (select email from spam)


              @list may now be INSERTed into a table, etc.



              I hope this helps.



              To use it for a .csv file or in VB, spike the code:



              declare @list as varchar(8000)
              set @list += @list (select '"'+email+',"' from spam)
              print @list


              and it produces ready-made code to use elsewhere:



              ".accountant,"
              ".bid,"
              ".buiilldanything.com,"
              ".club,"
              ".cn,"
              ".cricket,"
              ".date,"
              ".download,"
              ".eu,"


              One can be very creative.



              Thanks



              Nico






              share|improve this answer






























                1














                Isn't this a much simpler solution, if I correctly understand the question, of course.



                I want to load email addresses that are in a table called "spam" into a variable.



                select email from spam


                produces the following list, say:



                .accountant
                .bid
                .buiilldanything.com
                .club
                .cn
                .cricket
                .date
                .download
                .eu


                To load into the variable @list:



                declare @list as varchar(8000)
                set @list += @list (select email from spam)


                @list may now be INSERTed into a table, etc.



                I hope this helps.



                To use it for a .csv file or in VB, spike the code:



                declare @list as varchar(8000)
                set @list += @list (select '"'+email+',"' from spam)
                print @list


                and it produces ready-made code to use elsewhere:



                ".accountant,"
                ".bid,"
                ".buiilldanything.com,"
                ".club,"
                ".cn,"
                ".cricket,"
                ".date,"
                ".download,"
                ".eu,"


                One can be very creative.



                Thanks



                Nico






                share|improve this answer




























                  1












                  1








                  1







                  Isn't this a much simpler solution, if I correctly understand the question, of course.



                  I want to load email addresses that are in a table called "spam" into a variable.



                  select email from spam


                  produces the following list, say:



                  .accountant
                  .bid
                  .buiilldanything.com
                  .club
                  .cn
                  .cricket
                  .date
                  .download
                  .eu


                  To load into the variable @list:



                  declare @list as varchar(8000)
                  set @list += @list (select email from spam)


                  @list may now be INSERTed into a table, etc.



                  I hope this helps.



                  To use it for a .csv file or in VB, spike the code:



                  declare @list as varchar(8000)
                  set @list += @list (select '"'+email+',"' from spam)
                  print @list


                  and it produces ready-made code to use elsewhere:



                  ".accountant,"
                  ".bid,"
                  ".buiilldanything.com,"
                  ".club,"
                  ".cn,"
                  ".cricket,"
                  ".date,"
                  ".download,"
                  ".eu,"


                  One can be very creative.



                  Thanks



                  Nico






                  share|improve this answer















                  Isn't this a much simpler solution, if I correctly understand the question, of course.



                  I want to load email addresses that are in a table called "spam" into a variable.



                  select email from spam


                  produces the following list, say:



                  .accountant
                  .bid
                  .buiilldanything.com
                  .club
                  .cn
                  .cricket
                  .date
                  .download
                  .eu


                  To load into the variable @list:



                  declare @list as varchar(8000)
                  set @list += @list (select email from spam)


                  @list may now be INSERTed into a table, etc.



                  I hope this helps.



                  To use it for a .csv file or in VB, spike the code:



                  declare @list as varchar(8000)
                  set @list += @list (select '"'+email+',"' from spam)
                  print @list


                  and it produces ready-made code to use elsewhere:



                  ".accountant,"
                  ".bid,"
                  ".buiilldanything.com,"
                  ".club,"
                  ".cn,"
                  ".cricket,"
                  ".date,"
                  ".download,"
                  ".eu,"


                  One can be very creative.



                  Thanks



                  Nico







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 26 '16 at 16:50

























                  answered Apr 26 '16 at 16:40









                  Nico van NiekerkNico van Niekerk

                  113




                  113























                      0














                      I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.



                      declare @myVal int;
                      set @myVal = isnull((select a from table1), 0);



                      Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.






                      share|improve this answer




























                        0














                        I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.



                        declare @myVal int;
                        set @myVal = isnull((select a from table1), 0);



                        Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.






                        share|improve this answer


























                          0












                          0








                          0







                          I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.



                          declare @myVal int;
                          set @myVal = isnull((select a from table1), 0);



                          Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.






                          share|improve this answer













                          I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.



                          declare @myVal int;
                          set @myVal = isnull((select a from table1), 0);



                          Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 27 '18 at 20:50









                          G. Gordon NasseriG. Gordon Nasseri

                          111




                          111






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • 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%2fstackoverflow.com%2fquestions%2f10355694%2fsql-query-store-result-of-select-in-local-variable%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

                              Contact image not getting when fetch all contact list from iPhone by CNContact

                              count number of partitions of a set with n elements into k subsets

                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks