Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

sql - Selecting columns that are not all null

So I have a query that looks like this -

select 
case when @subType = 1 or @subType = 2 then id end as Id,
case when  @subType = 3 then name end as name
case when @subType = 3 or @subType = 2 then address end as address
from 
table

So the issue I have is, that if @subType is 3, then the column named ID will all be null. I then don't want to return this entire column. Conversely to that, if @subType is 2, then name would all be null so I don't want that entire column.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only way you could do this would be with dynamic SQL (as Gordon mentions). Provided this is a query, and not a function, view, then you could do this:

DECLARE @subType tinyint = 3;

DECLARE @SQL nvarchar(MAX);

SET @SQL = N'SELECT ' +
           STUFF(CASE WHEN @subType IN (1,2) THEN N',' + NCHAR(13) + NCHAR(10) + N'       id' ELSE N'' END + 
                 CASE WHEN @subType = 3 THEN N',' + NCHAR(13) + NCHAR(10) + N'       [name]' ELSE N'' END + 
                 CASE WHEN @subType IN (3,2) THEN N',' + NCHAR(13) + NCHAR(10) + N'       [address]' ELSE N'' END, 1, 10,N'') + NCHAR(13) + NCHAR(10) +
           N'FROM YourTable;';

PRINT @SQL; --Your debugging best friend.
--EXEC sp_executesql @SQL; --Uncomment to run the statement

But, if the query is coming from a presentation layer, then really that should be handling what columns are being displayed, not SQL Server

If you're passing parameters to the WHERE of your query as well, ensure that you parametrise the call to sp_executesql; do not inject the parameter values into the dynamic statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...