无法选择SQL变量

时间:2019-06-14 08:19:23

标签: sql tsql

我试图创建一个动态查询并执行它,在该查询中,表名应在运行时更改,表名应在运行时更改的模式为“ D_M”。请参阅代码以进一步说明。

以下是我无法执行的代码:

DECLARE @MyCursor 
CURSOR,@ChannelName NVARCHAR(max),@ChannelNumber NVARCHAR(max),@sqlstring NVARCHAR(max);BEGIN 
    SET @MyCursor = 
    CURSOR FOR 
      SELECT mirthdb.dbo.channel.NAME, 
             mirthdb.dbo.d_channels.local_channel_id 
      FROM   mirthdb.dbo.d_channels, 
             mirthdb.dbo.channel 
      WHERE  mirthdb.dbo.channel.id = mirthdb.dbo.d_channels.channel_id 
      AND    mirthdb.dbo.channel.NAME LIKE '0%' 
OPEN @MyCursor 
FETCH next 
FROM  @MyCursor 
INTO  @ChannelName, 
      @ChannelNumber; 

WHILE @@FETCH_STATUS=0 
BEGIN 
  SET @sqlstring = 'select' +(@ChannelName), 
    ('select count(*) from mirthdb.dbo.D_M'+@ChannelNumber) 
  EXEC(@sqlstring) 
  --print @ChannelNumber 
  FETCH next 
  FROM  @MyCursor 
  INTO  @ChannelName, 
        @ChannelNumber 
END 
CLOSE @MyCursor; 
DEALLOCATE @MyCursor; 
END; 

我正在尝试实现以下结果集: 频道名称:收到的邮件数 test_name1:2 test_name2:4 test_name3:0

0 个答案:

没有答案