Select Columns with prefix

63 Views Asked by At

A table I am using has 114 columns, but I only want to select columns that start with 'UDF_%'

Data:

Dept Number Employee Key UDF_F_Name UDF_L_Name UDF_Hire Date
243 111111 Employee 1 Test 3/18/2024
244 222222 Employee 2 Test 3/1/2024

I have attempted a few things I found on the internet to not avail:

Select c.Column_Name
    from INFORMATION_SCHEMA.columns as C
where c.Table_Name = 'JT_Employee'
    and c.COLUMN_NAME like 'UDF_%'

This provided all of the column names that I want, but it provided as rows only. Now I am trying to use that query as a sub-query to provide the column names:

Select
    (
    Select c.Column_Name
        from INFORMATION_SCHEMA.columns as C
    where c.Table_Name = 'JT_Employee'
        and c.COLUMN_NAME like 'UDF_%'
    )
From JT_Employee
Select column_name, table_name
from INFORMATION_SCHEMA.Columns
Where table_name in ('JT_Employee')
and column_name = 'UDF_%'

The final results I am hoping to obtain are the columns that start with 'UDF_%' and remove all of the others:

UDF_F_Name UDF_L_Name UDF_Hire Date
Employee 1 Test 3/18/2024
Employee 2 Test 3/1/2024

I was able to get the following to provide me the string I need of my column names but am unable to get it to activate as column name select in a different query

Select Distinct
    Stuff((Select c.Column_Name +', '
    from INFORMATION_SCHEMA.columns as C
    where c.Table_Name = 'JT_Employee'
        and c.COLUMN_NAME like 'UDF_%'
    FOR XML PATH ('')),1,0,'')
1

There are 1 best solutions below

2
pestomania On

@Siggemannen was able to the answer:

DECLARE @sql nvarchar(max)

SELECT  @sql = stuff((

SELECT  ',' + QUOTENAME(c.Column_Name)
FROM    INFORMATION_SCHEMA.columns AS C
WHERE   c.Table_Name = 'JT_Employee'
AND c.COLUMN_NAME LIKE 'UDF_%' 
ORDER BY ORDINAL_POSITION 
FOR xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 1, '')  

EXEC    ('select ' + @sql + ' from JT_Employee') –