简体   繁体   中英

Call function over every column sql

let's say I have a table with a lot of columns and I want to call same function on every of them (for example MAX ). Is it possible without listing all columns? That is instead of

Select max(col1), max(col2), max(col3)
from table1

write

Select max(col)
for col in table1.columns
from table1

There is no out of the box function to do that but since you have dynamic function tagged I assume that you want an example of dynamic code as well.

DECLARE @TableName VARCHAR(50) = 'put the table name here'
DECLARE @SqlCmd VARCHAR(MAX) = ''

SELECT @SqlCmd = @SqlCmd + ',MAX(' + QUOTENAME(c.name) + ') as ' + QUOTENAME(c.name)
        -- optional line break
        +CHAR(13)+CHAR(10)
FROM sys.columns c
INNER JOIN sys.tables t ON  c.object_id = t.object_id
WHERE t.name = @TableName
ORDER BY c.column_id

SET @SqlCmd = 'SELECT ' + STUFF(@SqlCmd,1,1,'') + ' FROM ' + QUOTENAME (@TableName)

--PRINT @SqlCmd
--SELECT @SqlCmd
EXEC (@SqlCmd)

Execute the dynamic query using sp_executesql .

DECLARE @sqlQuery NVARCHAR(MAX) = N'SELECT';

SELECT @sqlQuery = @sqlQuery + ' MAX(' + QUOTENAME(COLUMN_NAME) + ') AS ' + QUOTENAME(COLUMN_NAME) + ','
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table1';

SET @sqlQuery = LEFT(@sqlQuery, LEN(@sqlQuery) - 1) + ' FROM table1';

EXEC sp_executesql @sqlQuery;

Hope it's work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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