如何将查询作为字符串添加到另一个查询

时间:2011-12-17 21:08:00

标签: sql-server-2005

我需要生成一个查询:

SELECT @numberOfRecords = COUNT(*) FROM Car WHERE CarId not in (Select CarId from CarData)

目前我有:

DECLARE @sql NVARCHAR(255)
SET @sql='Select CarId from CarData'

DECLARE @numberOfRecords BIGINT
SELECT @numberOfRecords = COUNT(*) FROM Car WHERE CarId not in (@sql)

我正在尝试其他各种组合,例如'('坚果它不起作用。 我需要改变它才能让它发挥作用?

2 个答案:

答案 0 :(得分:2)

您正在寻找的是动态sql,有很多关于它的文章,如果您使用的是SQL Server,则需要使用sp_executesql

有一个示例here用于类似于您尝试的操作

你的解决方案看起来应该是这样的

DECLARE @carIdSql        NVARCHAR(255),
        @sql             NVARCHAR(MAX),
        @ParamDefinition NVARCHAR(MAX),
        @numberOfRecords BIGINT

SET @carIdSql='Select CarId from CarData';

SET @sql =
N'SELECT @numberOfRecordsOUT = COUNT(*) 
  FROM Car WHERE CarId not in (' + @carIdSql + ')'

SET @ParamDefinition = '@numberOfRecordsOUT BIGINT OUTPUT';

EXECUTE sp_executesql
  @sql,
  @ParamDefinition,
  @numberOfRecordsOUT = @numberOfRecords OUTPUT;

SELECT @numberOfRecords  

答案 1 :(得分:2)

您需要使用sp_executesql

DECLARE
@numberOfRecords       INT ,
@VariableSQL NVARCHAR(255),
@SQLStmt     NVARCHAR(255),
@paramtype   NVARCHAR(100)

SET @VariableSQL = 'Select CarId from CarData'

SET @SQLStmt = 'SELECT @counter = COUNT(1) FROM Car WHERE CarId NOT IN (' + @variablesql + ')'

SET @ParamType = '@counter int output'

EXEC sp_executesql @SQLStmt, @paramtype, @Counter = @numberOfRecords OUTPUT
PRINT @numberOfRecords