如何使用 SQL 中的 Case 语句将数据插入临时表
Posted
技术标签:
【中文标题】如何使用 SQL 中的 Case 语句将数据插入临时表【英文标题】:How to insert data into temp table using Case statement in SQL 【发布时间】:2021-12-30 07:07:56 【问题描述】:我正在尝试使用Case
语句将数据插入到临时表中,下面是我的代码,因此我收到此错误
子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。
我无法弄清楚我做错了什么。这是根据Case
语句中提供的特定条件将数据插入临时表的正确方法吗?
DECLARE @temp_idCol TABLE
(
uid int IDENTITY(1, 1),
id nvarchar(20)
)
DECLARE @_ThresholdOperator nvarchar(20) = '=',
@_Threshold_Val nvarchar(20) = '0.4'
INSERT INTO @temp_idCol (id)
SELECT
CASE
WHEN @_ThresholdOperator = '='
THEN (SELECT q.id
FROM [dbo].[Summit_Twitter_HashtagDetails] q
WHERE q.Ticket_ID IS NULL
AND q.SentimentAnalyis_Score = @_Threshold_Val
OR q.IsProcessedOrNot = 0)
WHEN @_ThresholdOperator = '>'
THEN (SELECT q.id
FROM [dbo].[Summit_Twitter_HashtagDetails] q
WHERE q.Ticket_ID IS NULL
AND q.SentimentAnalyis_Score > @_Threshold_Val
OR q.IsProcessedOrNot = 0)
WHEN @_ThresholdOperator = '<'
THEN (SELECT q.id
FROM [dbo].[Summit_Twitter_HashtagDetails] q
WHERE q.Ticket_ID IS NULL
AND q.SentimentAnalyis_Score < @_Threshold_Val
OR q.IsProcessedOrNot = 0)
END AS id
FROM
[dbo].[Summit_Twitter_HashtagDetails]
【问题讨论】:
case 是返回标量值而不是控制流语句的表达式 【参考方案1】:CASE
表达式只能返回 1 个值。
但是你可以使用IF
和ELSE
简化示例:
create table test (id int identity primary key, col decimal(9,1)); insert into test (col) values (0.1),(0.2),(0.3),(0.4),(0.5);
declare @ids table (id int); declare @_ThresholdOperator varchar(2) = '>', @_Threshold_Val nvarchar(20) = '0.3'; IF @_ThresholdOperator = '=' insert into @ids (id) select id from test where col = @_Threshold_Val; ELSE IF @_ThresholdOperator = '<' insert into @ids (id) select id from test where col < @_Threshold_Val; ELSE IF @_ThresholdOperator = '>' insert into @ids (id) select id from test where col > @_Threshold_Val; ELSE BEGIN insert into @ids (id) values (0); update @ids set id = id + 42; END; select * from @ids;
id |
---|
4 |
5 |
db小提琴here
额外
CASE
仍然可以在 WHERE
子句中使用。
只要它只返回 1 个值。
它只是不可分割。
insert into @ids (id)
select id from test
where case @_ThresholdOperator
when '=' then iif(col=@_Threshold_Val,1,0)
when '<' then iif(col<@_Threshold_Val,1,0)
when '>' then iif(col>@_Threshold_Val,1,0)
end = 1;
【讨论】:
谢谢@LukStorms,我也试过 If else ,它工作正常。 那很好。猜猜这真的不需要Dynamic Sql。 感谢您为案例声明提供的解决方案,我已根据需要对其进行了修改,并且效果很好。以上是关于如何使用 SQL 中的 Case 语句将数据插入临时表的主要内容,如果未能解决你的问题,请参考以下文章
如何从oracle sql中的选择计数中对rownum使用case语句?
SQL查询语句SELECT中带有case when嵌套子查询判断的问题