简体   繁体   English

T-SQL:从基于字符串的 SELECT 语句中排除列

[英]T-SQL: Exclude Columns from a SELECT statement based on string

My overall goal is to create new tables by selecting columns in existing tables with certain patterns/tags in their column names.我的总体目标是通过在列名中选择具有特定模式/标签的现有表中的列来创建新表。 This is in SQL Server.这是在 SQL Server 中。

For example, I have a common need to get all contact information out of a company table, and into its own contact table.例如,我有一个共同的需求,即从公司表中获取所有联系信息,并将其放入自己的联系表中。

I haven't been able to find a programmatic approach in SQL to express excluding columns from a SELECT statement based on string.我一直无法在 SQL 中找到一种编程方法来表示从基于字符串的SELECT语句中排除列。

When looking to options like the COL_NAME function, those require an ID arg, which kills that option for me.当寻找像COL_NAME函数这样的选项时,那些需要一个 ID arg,这对我来说会杀死那个选项。

Wishing there was something built in that could work like the following:希望有一些内置的东西可以像下面这样工作:

SELECT * 
FROM TABLE 
WHERE COL_NAME() LIKE 'FLAG%'

Any ideas?有任何想法吗? Open to anything!对任何事物开放! Thanks!!谢谢!!

One trick could be to firstly using the following code to get the column names you desire:一个技巧可能是首先使用以下代码来获取您想要的列名:

select * from information_schema.columns 
where table_name='tbl' and column_name like 'FLAG%'

Then concatenate them into a comma-delimited string and finally create a dynamic sql query using the created string as the column names.然后将它们连接成一个逗号分隔的字符串,最后使用创建的字符串作为列名创建一个动态 sql 查询。

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

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