如何在选择查询中选择表名?下面的查询返回大约200个表。在200张桌子中,大约10到15张桌子的id = 0。
如何在选择查询中选择表名?
预期结果:表名称,选择查询中的计数
select 'select count(*) from' + ' ' + name + ' ' + 'where id = 0 group by
id having count(*) > 1 ' from sysobjects
where id in ( select id from syscolumns where name = 'Id' )
and xtype = 'U'
and name like 'T%'
order by id
答案 0 :(得分:1)
假设问题中的查询对您有意义,这是您想要的吗?
select 'select ''' + name + ''' AS Name, count(*) from ' + name + ' where id = 0 group by
id having count(*) > 1' from sysobjects
where id in ( select id from syscolumns where name = 'Id' )
and xtype = 'U'
and name like 'T%'
order by id
答案 1 :(得分:1)
具有带有Id = 0
行的表:
DECLARE @SQL NVARCHAR(MAX) = ''
select @SQL = STUFF((SELECT ' union all select ''' + name + ''' AS TableName, count(*) from' + ' ' + name + ' ' + 'where id = 0 group by id having count(*) > 1' from sysobjects
where id in ( select id from syscolumns where name = 'Id' )
and xtype = 'U'
and name like 'T%'
order by id
FOR XML PATH, TYPE).value('.[1]', 'nvarchar(max)')
,1
,11
,''
)
EXEC sp_executesql @SQL