将动态查询的结果存储在变量中

时间:2014-09-15 14:36:10

标签: sql sql-server-2008

我知道这个问题已被提出,我已经在互联网上找到了一些解决方案......但我仍然无法使其正常工作。

所以..我必须创建一个SELECT查询并将结果存储在一个变量中(我不想要一个表变量)。 我的问题是表的名称也是一个变量。表名相应地改为WHILE,这是我的代码:

DECLARE @numRecord INT;
DECLARE @maxMacNumber INT;
SET @maxMacNumber = 500;
DECLARE @mac INT;
SET @mac = 0;
DECLARE @res FLOAT;
DECLARE @ap INT;
SET @ap = 0;
DECLARE @apString VARCHAR(2);
DECLARE @numRecordString VARCHAR(20);
DECLARE @tablename VARCHAR(500);
DECLARE @sql NVARCHAR(500);
DECLARE @varDefinition NVARCHAR(200);

WHILE @mac <= @maxMacNumber
BEGIN
     SET @numRecord = 6 + @mac * 390;
     SET @ap = 0;
     WHILE @ap < 2
     BEGIN
          SELECT @apString = CONVERT(VARCHAR,@ap);
          SELECT @numRecordString = CONVERT(VARCHAR, @numRecord);
          SELECT @rssiString = CONVERT(VARCHAR, @rssi); 
          SET @tablename = 'APDB.dbo.AP' + @apString;
          SET @sql = 'SELECT RSSI FROM ' + @tablename + ' WHERE ID=' + @numRecordString;
          SET @varDefinition = N'@res FLOAT OUTPUT';
          EXEC sp_executesql @sql, @varDefinition, @res = @res OUTPUT;
          PRINT @res;
          -- HERE I WILL DO SOMETHING WITH @res
      END;
END;

问题是,当我PRINT @res ...

时,它不会打印任何内容

1 个答案:

答案 0 :(得分:1)

这是相关的SQL代码:

      SET @sql = 'SELECT RSSI FROM ' + @tablename + ' WHERE ID=' + @numRecordString;
      SET @varDefinition = N'@res FLOAT OUTPUT';
      EXEC sp_executesql @sql, @varDefinition, @res = @res OUTPUT;
      PRINT @res;

您永远不会在SQL中设置@res。试试这个:

      SET @sql = 'SELECT @res = RSSI FROM ' + @tablename + ' WHERE ID=' + @numRecordString;
      SET @varDefinition = N'@res FLOAT OUTPUT';
      EXEC sp_executesql @sql, @varDefinition, @res = @res OUTPUT;
      PRINT @res;