我需要将下一列更新为包含特定数字的列。
ff是表C中的列。
C1_K | C1_ID | C2_K | C2_ID | C3_K | C3_ID
逻辑:
请指教。我需要更新匹配的K列旁边的列。感谢。
注意:
示例数据:
154 | NULL | 155 | SantoRyUu | 156 | NULL
如果选择155,SantoRyUu将会更新。
答案 0 :(得分:0)
(抛开设计问题。)
您必须按名称提及列,因为SQL Server没有“next to”的语法。您可以使用动态SQL执行此操作,但是很糟糕。这是一种可能性:
CREATE TABLE dbo.C
(
C1_K INT,
C1_ID VARCHAR(32),
C2_K INT,
C2_ID VARCHAR(32),
C3_K INT,
C3_ID VARCHAR(32)
);
INSERT dbo.C(C1_K, C2_K, C3_k)
SELECT 5,1,2
UNION ALL SELECT 2,5,7
UNION ALL SELECT 3,4,6;
DECLARE @MagicNumber INT;
SET @MagicNumber = 5;
UPDATE dbo.C SET
C1_ID = CASE C1_K WHEN @MagicNumber THEN 'yes' ELSE C1_ID END,
C2_ID = CASE C2_K WHEN @MagicNumber THEN 'yes' ELSE C2_ID END,
C3_ID = CASE C3_K WHEN @MagicNumber THEN 'yes' ELSE C3_ID END;
SELECT * FROM dbo.C;
结果:
C1_K C1_ID C2_K C2_ID C3_K C3_ID
---- ----- ---- ----- ---- -----
5 yes 1 NULL 2 NULL
2 NULL 5 yes 7 NULL
3 NULL 4 NULL 6 NULL
答案 1 :(得分:0)
如果你在* _K列上有索引,你应该试试这个
select C1_id
from table where c1_k = 155
union all
select C2_id
from table where c2_k = 155
union all
select C3_id
from table where c3_k = 155
如果这些列上没有索引
select
--coalesce(C1_id,c2_id,c3_id) --if you are sure other two columns values will be null
case
when c1_k = 155 then c1_id
when c2_k = 155 then c2_id
when c3_k = 155 then c3_id
end --in case you have values for other columns as
--well like for 154 you might not have null but some other value..
from table where c1_k = 155
or c2_k = 155
or c3_k = 155
如果您有更多这样的列,请更改上述查询。 但最好的解决方案是让你的colums成行...