SQL Column Name wildcard

一笑奈何 提交于 2021-01-28 07:56:06

问题


I have a table with 30+ fields and I want to quickly narrow my selection down to all fields where column name start with 'Flag'.

select * Like Flag% from Table1

回答1:


You will want to build a dynamic query as explained here: https://stackoverflow.com/a/4797728/9553919

SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE table_name = 'Foods'
        AND table_schema = 'YourDB'
        AND column_name LIKE 'Vegetable%'



回答2:


This SQL Statement should be useful. You may be able to simplify it but it does work.

Edit2: I just now saw your pervasive-sql tag. Unfortunately I've never worked with that and don't know if the syntax is compatible with MS SQL Server. I'll let my answer here in case it helps others, but wanted to share that I tested this using SQL Server.

Edit: SCHEMA_NAME function isn't necessary. You can replace SCHEMA_NAME(schema_id) with the name of your schema in single quotes if you want, but either will work.

 SELECT t.name AS table_name,
      SCHEMA_NAME(schema_id) AS schema_name,
      c.name AS column_name
 FROM 
     sys.tables AS t
 INNER JOIN 
     sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
 WHERE 
      t.name = 'Table1' AND
      c.name Like 'Flag%'
 ORDER BY 
     c.name

or

 SELECT t.name AS table_name,
      'MySchema' AS schema_name,
      c.name AS column_name
 FROM 
     sys.tables AS t
 INNER JOIN 
     sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
 WHERE 
      t.name = 'Table1' AND
      c.name Like 'Flag%'
 ORDER BY 
     c.name



回答3:


To do this, you will need to query the system tables for the columns associated to the table and filter them to what you want. From there, place them into a variable table and create a CSV of columns. From there, you can dynamically construct your query as needed. The below example should help you get started.

DECLARE @tableName VARCHAR(100) = 'dbo.SomeTable'
DECLARE @columnNames TABLE
(
    Id INT IDENTITY PRIMARY KEY,
    ColumnName VARCHAR(100)
)

--Grabs all of the columns into a variable table
INSERT INTO @columnNames (ColumnName)
SELECT
    [name]
FROM sys.columns
WHERE
    [object_id] = OBJECT_ID(@tableName)
AND
    [name] LIKE '%Flag'

DECLARE @columns VARCHAR(1000)

--Creates a CSV of columns
SET @columns =
    STUFF(
    (
        SELECT
            ',' + ColumnName
        FROM @columnNames
        FOR XML PATH(''))
    ,1,1,'')

DECLARE @selectStatement NVARCHAR(4000) = CONCAT('SELECT ', @columns, ' FROM ', @tableName)

PRINT @selectStatement
EXEC @selectStatement 


来源:https://stackoverflow.com/questions/49496911/sql-column-name-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!