有什么方法可以在SQL中有条件地打印列?可以说
Select FirstName, LastName, RollNumber, Subject, Marks From Student
给出5列FirstName, LastName, RollNumber, Subject, Marks
的输出。它还接受一个参数@NameType
。如果为@NameType = 'First'
,则输出应仅为FirstName, RollNumber, Subject, Marks
。同样,如果为@NameType = 'Second'
,则输出应仅为SecondName, RollNumber, Subject, Marks
,不包括列FirstName
。如何实现?
Declare @NameType nvarchar(max);
Set @NameType='First'
Select FirstName, LastName, RollNumber, Subject, Marks From Student
答案 0 :(得分:1)
DECLARE @NameType VARCHAR(10)
SET @NameType = 'First';
SELECT CASE WHEN @NameType = 'First' THEN FirstName
WHEN @NameType = 'Second' THEN LastName END as [Name]
,RollNumber
,Subject
,Marks
FROM Student;
答案 1 :(得分:0)
听起来像你的后世一样
DECLARE @NameType varchar(6); --no reason to be a `MAX`, Second is only 6 characters long,
--and it doesn't need to be an nvarchar, as neither string contains unicode characters
SET @NameType = 'First';
SELECT CASE @NameType WHEN 'First' THEN FirstName
WHEN 'Second' THEN LastName
END AS [Name],
RollNumber,
Subject,
Marks
FROM Student;
答案 2 :(得分:0)
select
case when @NameType = 'First' then FirstName
when @NameType = 'Second' then SecondName end ColName,
RollNumber, Subject, Marks From Student