--那个帖里掉了一个空格,不好意思。
DECLARE @SQL VARCHAR(8000)
SET @SQL = ''
SELECT @SQL = @SQL + 'SELECT ' + TableName + ' AS 表名,COUNT(1) AS 数量 FROM ' +
    TableName + ' WHERE infoTitle=''hello'' UNION ALL ' FROM TIndex
SET @SQL = LEFT(@SQL, LEN(@SQL) - 10)
EXEC(@SQL)

解决方案 »

  1.   

    select * from(select TableName from TIndex)a
      

  2.   

    主要不是掉空格,而是少单引号DECLARE @SQL VARCHAR(8000)
    SET @SQL = ''
    SELECT @SQL = @SQL + 'SELECT ''' + TableName + ''' AS 表名,COUNT(1) AS 数量 FROM ' +
        TableName + ' WHERE infoTitle=''hello'' UNION ALL ' FROM TIndex
    SET @SQL = LEFT(@SQL, LEN(@SQL) - 10)
    EXEC(@SQL)
      

  3.   

    set nocount on
    declare @rowcount int
    select distinct @rowcount=count(*) from tindex
    declare aaa cursor local scroll
    for
    select distinct TableTableName from tindex
    open aaa
    declare @iii nvarchar(max)
    declare @jsq int
    set @jsq=1
    declare @sql nvarchar(max)
    while @jsq<=@rowcount
    begin
    fetch absolute @jsq from aaa into @iii
    set @sql='select * from '+@iii
    select @iii
    exec sp_executesql @sql
    set @jsq = @jsq + 1
    end
    set nocount off
    看我的哈哈
      

  4.   

    ALTER PROCEDURE [dbo].[aaaaaaaaaaaaaaaa]
    AS
    BEGIN
    set nocount on
    declare @rowcount int
    select distinct @rowcount=count(*) from t_index
    declare aaa cursor local scroll
    for
    select distinct name from t_index
    open aaa
    declare @iii nvarchar(max)
    declare @jsq int
    set @jsq=1
    declare @sql nvarchar(max)
    while @jsq<=@rowcount
    begin
    fetch absolute @jsq from aaa into @iii
    set @sql='select count(*) from '+@iii+ ' where infoTitle=''hello'''
    select @iii as 表名
    exec sp_executesql @sql
    set @jsq = @jsq + 1
    end
    set nocount off
    END