Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign data to a user-defined table type from Select query in SQL Server 2014

I have a stored procedure which retrieves three columns from multiple tables. I want to get the results in a user defined multi-valued table and pass the variable to another procedure to perform operations on the variable data.

However it is not working. Any idea why it this not working?

--This is the initial stored procedure
Create Procedure spSelectData
AS
BEGIN
    Select 
        Userid, first_date, last_update
    From Users
END

--This is to create the table type.
Create type Task1TableType AS TABLE
(
     Userid nvarchar(20),
     First_date datetime,
     Last_update datetime
)

--Declare a table of type 
DECLARE @firstStep AS Task1TableType
(
    Userid nvarchar(20),
    First_date datetime,
    Last_update datetime
)

Insert @firstStep EXEC spSelectData

Select * from @firstStep

-- This is the procedure 1
CREATE PROC spTest1
   @TTType Task1TableType READONLY
AS
BEGIN
    Select * from @TTType
END
like image 896
Mian Asbat Ahmad Avatar asked Oct 08 '15 10:10

Mian Asbat Ahmad


People also ask

Can I create a table from a SELECT statement?

You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl; MySQL creates new columns for all elements in the SELECT .

How do you assign a value to a SELECT query?

To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Which query is used to create a user-defined data type?

To create a user-defined data type. In Object Explorer, expand Databases, expand a database, expand Programmability, expand Types, right-click User-Defined Data Types, and then click New User-Defined Data Type.


1 Answers

The problem is here:

DECLARE @firstStep AS Task1TableType
(
    Userid nvarchar(20),
    First_date datetime,
    Last_update datetime
)


Insert @firstStep
EXEC spSelectData;

Should be:

DECLARE @firstStep AS Task1TableType;

Insert INTO @firstStep
EXEC spSelectData;

EXEC spTest1
  @firstStep;

There is no need to defining columns where type is defined, and INSERT require INTO clause. After that change your code works.

SqlFiddleDemo

like image 64
Lukasz Szozda Avatar answered Oct 14 '22 10:10

Lukasz Szozda