sql select with column name like

前端 未结 8 1190
盖世英雄少女心
盖世英雄少女心 2020-12-02 15:46

I have a table with column names a1,a2...,b1.b2....

How can I select all those with column names like a%?

8条回答
  •  一生所求
    2020-12-02 16:18

    Thank you @Blorgbeard for the genious idea.

    By the way Blorgbeard's query was not working for me so I edited it:

    DECLARE @Table_Name as VARCHAR(50) SET @Table_Name = 'MyTable'          -- put here you table name
    DECLARE @Column_Like as VARCHAR(20) SET @Column_Like = '%something%'    -- put here you element
    DECLARE @sql NVARCHAR(MAX) SET @sql = 'select '
    
    SELECT @sql = @sql + '[' + sys.columns.name + '],'
    FROM sys.columns 
    JOIN sys.tables ON sys.columns.object_id = tables.object_id
    WHERE sys.columns.name like @Column_Like
    and sys.tables.name = @Table_Name
    
    SET @sql = left(@sql,len(@sql)-1) -- remove trailing comma
    SET @sql = @sql + ' from ' + @Table_Name
    
    EXEC sp_executesql @sql
    

提交回复
热议问题