使用WHEN子句或类似的东西显示和不显示SELECT语句中的列?

时间:2017-06-02 04:54:30

标签: mysql sql sql-server tsql

我想写一个如下的查询:

我不想使用where子句。我想在-----写一些不再显示A的东西。我认为这个是不可能的,因为在那之后我们可以将值分配给A而不是删除A

Select
(CASE WHEN A>0 THEN (A) ELSE ----- END),
(CASE WHEN A>0 THEN (A) ELSE ----- END)
from table

1 个答案:

答案 0 :(得分:0)

这是SQL Server实现(假设只删除一列)。数据库[学校]

表格脚本

CREATE TABLE [dbo].[Matches]
(
    [FootballerName] [varchar](100) NULL,
    [Goal] [int] NULL,
    [Tournament] [varchar](100) NULL
)  

插入声明

insert into Matches(FootballerName,Goal,Tournament)
select 'Messi ', 3 ,'La liga' union
select 'Ronaldo ', 5 ,'UEFA' union
select 'Surez ', 2 ,'La liga';

查询结果(从select语句中删除列目标)

Declare @TableName varchar(100)
SET @TableName='Matches'
Declare @ColumnToRemove varchar(1000)
SET @ColumnToRemove='Goal'

DECLARE @ListOfColumn VARCHAR(8000)
SELECT @ListOfColumn = COALESCE(@ListOfColumn + ',', '') + CAST(column_name AS VARCHAR)
FROM INFORMATION_SCHEMA.columns
WHERE TABLE_NAME=@TableName  and table_catalog='School' and Column_Name<>@ColumnToRemove

Declare @Query varchar(1000)
SET @Query ='Select ' + @ListOfColumn +' from ' +@TableName
EXEC(@Query)

查询结果(删除一列)

FootballerName  Tournament
--------------  ---------------
Messi           La liga
Ronaldo         UEFA
Surez           La liga

结果(使用所有列)

FootballerName  Goal    Tournament
--------------  ----    ----------- 
Messi           3       La liga
Ronaldo         5       UEFA
Surez           2       La liga