Can TSQL select into an array or variable?

BenTam-3003 686 Reputation points
2022-01-12T14:15:48.87+00:00

Dear All,

Can a select command put its result into an array (or a variable) as follows?

 Select * from student into array myArray          (note: this is not a correct statement)
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,555 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Olaf Helper 40,901 Reputation points
    2022-01-12T14:21:47.303+00:00

    Databases don't have object types like array, but tables.
    You can define a variable as table and insert with a select statement data into, example:

    declare @test table (object_id int, name sysname);
    
    insert into @test
    select object_id, name
    from sys.objects;
    
    select *
    from @test
    
    1 person found this answer helpful.
    0 comments No comments

  2. Erland Sommarskog 101.4K Reputation points MVP
    2022-01-12T22:26:34.69+00:00

    The syntax is almost correct

    SELECT *
    INTO Array
    FROM Student
    

    This will create a new table called Array which is a copy of Student. But it is a table, not an array.

    I think Postgres has arrays, but I don't understand why. As Olaf says, in a relational database you work with tables.

    0 comments No comments

  3. LiHong-MSFT 10,046 Reputation points
    2022-01-13T02:07:30.627+00:00

    Hi,@BenTam-3003
    We cannot insert the queried data into the array,which is not supported in SQL server.
    For more details about 'insert into',please refer to this document.
    But we can use local table variable DECLARE @TempTable or temporary table #TempTable to store the result of select command .
    You can also combine query results into strings or XML documents,like this:

    DECLARE @STR VARCHAR(8000)  
    SELECT @STR=ISNULL(@STR+',','')+Stu_ID FROM Student  
    PRINT @STR  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  4. Olaf Helper 40,901 Reputation points
    2022-01-13T10:59:24.903+00:00

    not script, that will create a C# array or a C# variable.

    Nearly, you can use a data reader, see examples at SqlCommand Class

    0 comments No comments