【问题标题】:Select all rows in a table of certain type选择特定类型表中的所有行
【发布时间】:2013-04-22 22:25:14
【问题描述】:

我使用的是 SQL Server 2005,需要编写一个 select 语句来选择表中的所有行,但只针对某些类型的列。在我的情况下,我想要除那些之外的所有列xml、text、ntext、image 或非二进制 CLR 用户定义类型列的类型。

这就是问题所在。如果你想知道我为什么这样做,请继续阅读。我正在使用EXCEPT 来识别两个数据库中每个表之间的差异,类似于这个问题中概述的内容:SQL compare data from two tables。我不明白为什么评论中建议使用INTERSECT,所以我改用 UNION ALL。

我使用的代码是:

(select *, 'table a first' as where_missing from A EXCEPT select *,'table a first' as where_missing from B)
union all
(select *,'table b first' as where_missing from B EXCEPT select *, 'table b first' as where_missing from A)

某些表包含不适用于EXCEPT 的列类型。因此我不想选择那些列。我可以从 information_schema.columns 获取此信息,但是有没有一种很好的方法可以在上面的示例中使用它来代替“*”?

谢谢!

【问题讨论】:

  • 请提供好的问题或解释。这很令人困惑。

标签: sql tsql sql-server-2005 compare except


【解决方案1】:

我认为除了使用动态 SQL 之外没有其他方法可以做到这一点。首先选择列:

declare @columns nvarchar(max);
select @columns = stuff( 
    (select ', ' + c.name
    from sys.tables t
    join sys.columns c on t.object_id = c.object_id
    join sys.types ty on c.system_type_id = ty.system_type_id
    where t.name = 'A'
    and ty.name not in ('text', 'ntext', 'xml', 'image')
    for xml path(''))
, 1, 2, '');

然后运行查询:

declare @sql nvarchar(max);
set @sql = 'select ' + @columns + ', ''table a first'' as where_missing from A';
exec (@sql);

【讨论】:

  • 这成功了。我用它创建了一个存储过程,它采用两个数据库名称和一个表名称并返回所有差异。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多