Question

I'm using SQL Server 2005 and need to write a select statement that selects all of the rows within the table but only for columns of certain types. In my case I want all columns except those of type xml, text, ntext, image, or nonbinary CLR user-defined type columns.

That is the question. If you want to know why I'm doing this read on. I'm using EXCEPT to identify differences between each table in two databases similar to what is outlined in this question: SQL compare data from two tables. I don't understand why INTERSECT was suggested in the comment so I'm using UNION ALL instead.

The code I'm using is:

(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)

Some of the tables contain column types which don't work with EXCEPT. Therefore I don't want to select those columns. I can get this info from information_schema.columns but is there a nice way that I can then use that in my example above in place of the "*"?

Thanks!

Was it helpful?

Solution

I don't think there is a way to do it other than using dynamic SQL. First select columns:

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, '');

Then run the query:

declare @sql nvarchar(max);
set @sql = 'select ' + @columns + ', ''table a first'' as where_missing from A';
exec (@sql);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top