根据case / when语句将多个值插入表结构中

时间:2022-04-17 22:26:42

I have the need to do this.

我有必要这样做。

Declare @something varchar(100)
Declare @tempdata TABLE (temp varchar(100))

INSERT INTO @tempdata (temp) select case 
       when @something is null then 'temp1','temp2'
       else @something
       end

select * from @tempdata

Looks like inserting multiple values into the @tempdata array based on when condition is null, is not valid.

看起来根据条件为空时将多个值插入@tempdata数组,无效。

How do I add multiple values to @tempdata when @something is not set.

如果未设置@something,如何向@tempdata添加多个值。

I tried doing this

我试过这样做

when @something is null then 'temp1,temp2'

and then tried to split it by delimiter comma and then add to @tempdata, but splitting in sql doesn't look easy.

然后尝试用分隔符逗号分割它,然后添加到@tempdata,但在sql中拆分看起来并不容易。

Thanks for looking.

谢谢你的期待。

1 个解决方案

#1


You need to use an IF statement, followed by inserting with a SELECT... UNION ALL.

您需要使用IF语句,然后使用SELECT ... UNION ALL插入。

Declare @something varchar(100)
Declare @tempdata TABLE (temp varchar(100))

IF @something is null
BEGIN
    INSERT INTO @tempdata (temp)
    SELECT 'temp1' UNION ALL
    SELECT 'temp2'
END

select * from @tempdata

#1


You need to use an IF statement, followed by inserting with a SELECT... UNION ALL.

您需要使用IF语句,然后使用SELECT ... UNION ALL插入。

Declare @something varchar(100)
Declare @tempdata TABLE (temp varchar(100))

IF @something is null
BEGIN
    INSERT INTO @tempdata (temp)
    SELECT 'temp1' UNION ALL
    SELECT 'temp2'
END

select * from @tempdata