我有一个存储过程,它会联合一些数据并返回。在最大值时,SP将返回符合where条件的3行。
如果没有符合条件的数据,我是否可以强制SP返回空白行?
这就是我的SP的样子:
SELECT Top 1 Col1, 'FirstResult' FROM Table T1
where SomeColumn='whatever'
UNION ALL
SELECT Top 1 Col2, 'SecondResult' FROM Table T1
where SomeColumn='whatever'
UNION ALL
SELECT Top 1 Col3, 'ThirdResult' FROM Table T1
where SomeColumn='whatever'
即使条件不匹配,我也要总是给我3行。当然,结果集中的数据将为空或NULL
。
答案 0 :(得分:1)
您可以在此处演示此答案中的查询不使用任何行:http://www.sqlfiddle.com/#!3/51d1c/3
在YourTable中有一行:http://www.sqlfiddle.com/#!3/ad1e8/1
这是一个应该返回您要找的内容的程序:
CREATE PROCEDURE pExample_Get3ForcedRows
@FirstMatch VARCHAR(50)
,@SecondMatch VARCHAR(50)
,@ThirdMatch VARCHAR(50)
AS
BEGIN
DECLARE @ForceTable TABLE
(
MatchColumn VARCHAR(50) NOT NULL
)
INSERT @ForceTable (MatchColumn) VALUES (@FirstMatch),(@SecondMatch),(@ThirdMatch)
SELECT
T.Col1
, T.ResultColumn
FROM @ForceTable F
LEFT JOIN YourTable T
ON T.SomeColumn = F.MatchColumn
END
GO
答案 1 :(得分:0)
DECLARE @table (Col1 varchar, String2 varchar)
IF ( (SELECT COUNT(*) FROM Table T1 WHERE SomeColumn='whatever')>0 )
INSERT INTO @table
SELECT Top 1 Col1, 'FirstResult' FROM Table T1 WHERE SomeColumn='whatever'
ELSE
INSERT INTO @table
SELECT NULL AS Col1, ''
IF ( (SELECT COUNT(*) FROM Table T1 WHERE SomeColumn='whatever')>0 )
INSERT INTO @table
SELECT Top 1 Col2, 'secondResult' FROM Table T1 WHERE SomeColumn='whatever'
ELSE
INSERT INTO @table
SELECT NULL AS Col2, ''
IF ( (SELECT COUNT(*) FROM Table T1 WHERE SomeColumn='whatever')>0 )
INSERT INTO @table
SELECT Top 1 Col3, 'thirdResult' FROM Table T1 WHERE SomeColumn='whatever'
ELSE
INSERT INTO @table
SELECT NULL AS Col3, ''
RETURN @table
不知道是否有更优雅的版本,但这应该有用。