Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Table Variable in Dynamic Query

Tags:

sql

sql-server

I want to use Table Variable instead of Temp Table but My main query construction is Dynamic . Dynamic query is in single quote so how can I fetch data from @TableVariable. I dont want to remove dynamic query because some of parameter will added later.

e.g. following is error code , where I have wrote table variable into Dynamic Query........

/*Declare Table Variable*/
DECLARE @TempVehicles TABLE
    (
        [VehicleID] INT
    )   
/*Insert data into Table Variable*/
INSERT INTO @TempVehicles
(
    [VehicleID]
)
SELECT  VehicleID
FROM tbl_Vehicles

/*Dynamic Query and Main SQL Construction*/
DECLARE @SQL NVARCHAR(MAX)
SET @SQL ='SELECT Cust_ID,A.VehicleID,GISInfo 
           FROM @TempVehicles A INNER JOIN tbl_GISData B ON A.VehicleID=B.VehicleID'

EXECUTE SP_EXECUTESQL @SQL

Help me , in this .

Thanks in Advance.

like image 795
Anvesh Avatar asked May 06 '13 06:05

Anvesh


1 Answers

Try This :

CREATE TYPE IntegerTableType AS TABLE (ID INT);
go

DECLARE @TempVehicles IntegerTableType; 

INSERT  @TempVehicles
values (1);





DECLARE @SQL NVARCHAR(MAX);
SET @SQL ='SELECT * 
           FROM @TempVehicles;';


EXECUTE SP_EXECUTESQL @SQL,N'@TempVehicles IntegerTableType READONLY',
@TempVehicles;
like image 60
Ravi Singh Avatar answered Oct 06 '22 13:10

Ravi Singh