Select 来自多个 table(由另一个 select 传递)

Select from multiple table (passed by another select)

问题已更新。

我想要实现的是获取 description 字段中 emptynull 的新表列表。 (新表意味着带有前缀 new_)并且所有表都有描述字段。

Table定义:

create table topic (id int, description varchar(255));
create table comment (id int, description varchar(255));
create table author (id int, description varchar(255));
create table new_topic (id int, description varchar(255));
create table new_comment (id int, description varchar(255));
create table new_author (id int, description varchar(255));

示例数据和描述:

insert into new_topic (id, description) values (1, null);
insert into new_topic (id, description) values (2, 'This is topic description');
insert into new_comment (id, description) values (1, null);
insert into new_comment (id, description) values (2, null);
insert into new_author (id, description) values (1, 'This is casual first author.');
insert into new_author (id, description) values (2, 'This is casual second author.');

正如您在我的示例中注意到的那样,我的示例数据的理想输出应该是:

table_name:
new_topic
new_comment

我的实际解决方案有效,但我需要手动添加表格并且重复了很多次。

select  distinct 'new_topic' as table_name
from new_topic where description is null
select distinct 'new_comment' as table_name
from new_comment where description is null
select  distinct 'new_author' as table_name
from new_author where description is null

我的解决方案输出如下:

table_name
new_topic
table_name
new_comment
table_name

我还创建了 SELECT 来获取所有新表:

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE 'new_%' AND TABLE_TYPE = 'BASE TABLE'

这可能是我之前 select 的切入点,但我不知道如何将这两者联系起来。

我的解决方案也可用于 dbfiddle

你能不能只做:-

select table_name from information_schema.columns 
where table_name like 'prefix_%' and (column_name is null or column_name='')

哦,我想我明白你在追求什么。是的,这需要动态 sql。另外,请注意,您要查找名称为 new_ 的所有 table 的查询不太正确。下划线是通配符模式检查。所以当你不想要它时,return 一个名为 "news" 的 table。将下划线括在方括号中以解决此问题。以下是我将如何处理此类查询。代码中的注释应该解释这一点。

declare @SQL nvarchar(max) = '' --this must be initialized to an empty string for this to work.

select @SQL = @SQL + 'select distinct TableName = ''' + t.name + ''' from ' + quotename(t.name) + ' where description is null union all '
from sys.tables t
where name like 'new[_]%' --need the square brackets because the underscore is a wildcard so you might get false positives


select @SQL = left(@SQL, len(@SQL) - 10)

--this will show you the dynamic sql
select @SQL

--once you are satisfied the dynamic sql is correct uncomment the next line to execute it
--exec sp_executesql @SQL