简体   繁体   English

SQL Server查询:获取另一个表的字段中不存在的列的列表

[英]SQL Server Query: Get a List of Columns Which Don't Exist in Another Table's Field

I need to select all the columns names only from a SPLANNING_ROOMDATA2 table in such way that those names should not exist in a comma separated list of column names in another table. 只需要从SPLANNING_ROOMDATA2表中选择所有列名称 ,这样这些名称就不应存在于另一个表中以逗号分隔的列名称列表中。 Here is my query in a C# ASP.NET application. 这是我在C#ASP.NET应用程序中的查询。 My query generates an error like ' syntax error near Where '. 我的查询生成一个错误,例如“ syntax error near Wheresyntax error near Where ”。

  SqlCommand cmd = new SqlCommand("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Splanning_RoomData2' where COLUMN_NAME NOT IN (SELECT ATTRIBUTENAME FROM SPLANNING_RESTRICTED_ATTRIBUTES)", con);//get only column names

Note, if I remove the second Where clause then I do get a list of columns but that is not what I desire. 注意,如果我删除第二个Where子句,那么我会得到一个列列表,但这不是我想要的。 I have done some searches but none met my needs. 我进行了一些搜索,但没有一个满足我的需求。

***Edit: As of now, none of the answers are working. ***编辑:截至目前,所有答案均无效。 I am going to try to change the splanning_restricted_attributes table's to allow one restricted attributed per row--instead of comma separated one. 我将尝试更改splanning_restricted_attributes表,以允许每行分配一个限制属性,而不是用逗号分隔一个限制属性。 Thanks all. 谢谢大家 ** **

You should not store lists as comma separated values. 您不应该将列表存储为逗号分隔的值。 They should be in a separate table, called a junction table with one row per column and table. 它们应位于单独的表中,称为联结表,每列和表每行一行。

Sometimes, though, you are stuck with such a structure. 但是,有时您会陷入这种结构。 Here is one method for getting what you need: 这是一种获取所需内容的方法:

select c.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS c LEFT JOIN
     SPLANNING_RESTRICTED_ATTRIBUTES ra
     ON ',' + lower(ra.ATTRIBUTENAME) + ',' LIKE '%,' + lower(c.column_name) + ',%'
where TABLE_NAME = 'Splanning_RoomData2' and ra.ATTRIBUTENAME is null;

Use AND instead of WHERE twice 两次使用AND而不是WHERE

SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='Splanning_RoomData2' 
AND COLUMN_NAME NOT IN (SELECT ATTRIBUTENAME 
                        FROM SPLANNING_RESTRICTED_ATTRIBUTES)", con);

I am just posting the updated answer of @Gordon Linoff answer try the query as, 我只是发布@Gordon Linoff答案的更新答案,尝试将查询作为,

select c.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS c JOIN
     SPLANNING_RESTRICTED_ATTRIBUTES ra
     ON ',' + lower(ra.ATTRIBUTENAME) + ',' NOT LIKE '%,' + lower(c.column_name) + ',%'
where c.TABLE_NAME = 'Splanning_RoomData2';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM