EXEC('select ' + @RecordCount + ' = count(ID) from t where ' + @condition)
@condition包含有列名,这样写运行不了,正确的写法该怎么写?
想要执行的结果和下面差不多,就是后面多了个条件变量:
select @RecordCount = count(ID) from t

解决方案 »

  1.   

    你的写法没有错
    关键是@condition如何写--比如
    set @condition='1=1'
    --或
    SET @condition='col1=''xxx'''示例CREATE TABLE T
    (
    [ID] INT,
    [NAME] VARCHAR(20)
    )declare @RecordCount varchar(20),@condition varchar(1000)
    SELECT @RecordCount='GGG',@condition='1=1'
    EXEC('select '+@RecordCount +' = count(ID) from   t   where   '   +   @condition)DROP TABLE T
      

  2.   

    --> Sample 1
    declare @SQL nvarchar(1000), @RecordCount int, @condition nvarchar(200)
    set @condition = 'id = 1'
    set @SQL = 'select @RecordCount = count(1) from syscolumns where ' + @condition
    exec sp_executesql @SQL, N'@RecordCount int output', @RecordCount output
    select @RecordCount
    go--> Sample 2
    declare @SQL nvarchar(1000), @RecordCount int, @condition nvarchar(200)
    set @condition = 'name = ''id'''
    set @SQL = 'select @RecordCount = count(1) from syscolumns where ' + @condition
    exec sp_executesql @SQL, N'@RecordCount int output', @RecordCount output
    select @RecordCount
    go
      

  3.   

    2楼 set @SQL = 'select @RecordCount = count(1) from syscolumns where ' + @condition少写了个N,set @SQL = N'select @RecordCount = count(1) from syscolumns where ' + @condition