7

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.

4

2 回答 2

11

尝试这个 :

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;
于 2013-05-06T07:16:22.443 回答
4

作为替代解决方案,您可以使用 #TempVehicles 而不是将其存储在变量中。

SELECT  VehicleID 
    into #TempVehicles
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; 
           Drop Table #TempVehicles'

EXECUTE SP_EXECUTESQL @SQL

尝试并检查它是否符合您的要求。

于 2013-05-06T07:15:30.373 回答