[英]sql select update multiple column and check not null before update
I have two tables. 我有两张桌子。
Table1 structure NOT NULL. Table1结构NOT NULL。
Table2 some value NULL. Table2的一些值为NULL。
I want update table2 to table1 , 我想将table2更新为table1,
I want when select value if null don't update and skip next column have value to update. 我想在选择值(如果为null时不更新)时跳过,并跳过下一列进行更新。
My Table 我的桌子
table1 value(table1) table2 value(table2)
t1ID 1234 t2ID 1234
t1Name Bear t2Name null
t1Adress 87/25 t2Adress 99/77
t1Tel 01254798535 t2Tel null
My Code 我的密码
UPDATE table1
SET t1Name = (SELECT t2Name
FROM table2
WHERE t2Name IS NOT NULL
),
t1Adress = (SELECT t2Adress
FROM table2
WHERE t2Adress IS NOT NULL
),
t1Tel = (SELECT t2Tel
FROM table2
WHERE t2Tel IS NOT NULL
)
FROM table1,table2
WHERE t1ID = '1234' AND t2ID ='1234'
When I execute I get error: 当我执行我得到错误:
SQL error : Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value.
SQL错误:消息512,级别16,状态1,行1子查询返回了多个值。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。 The statement has been terminated.
该语句已终止。
How can I fix it? 我该如何解决?
I think you intend: 我认为您打算:
UPDATE t1
SET t1Name = COALESCE(t2.t2Name, t1.t1Name),
t1Adress = COALESCE(t2.t2Adress, t1.t1Adress),
t1Tel = COALESCE(t2.t2Tel, t1.t2Tel)
FROM table1 t1 JOIN
table2 t2
ON t1.t1id = t2.t2id
WHERE t1.t1ID = 1234;
Note that I removed the single quotes on '1234'
. 请注意,我删除了
'1234'
上的单引号。 Id
s are usually numbers so they should be compared to numbers. Id
通常是数字,因此应该将它们与数字进行比较。
Your code fails because you are using subqueries instead of the values from the join
. 您的代码失败,因为您使用的是子查询,而不是
join
的值。 You seem to have multiple rows in table2
, so you are getting the subquery returned more than one row error. 您似乎在
table2
有多行,所以您得到的子查询返回的错误多于一行。
The following query replaces the null values with table1 values and updates the rest from table2 values 以下查询将空值替换为table1值,并更新table2值中的其余值
UPDATE T1 SET T1.t1Name = IsNull(T2.t2Name,T1.t1Name),
T1.t1Adress = IsNull(T2.t2Adress,T1.t1Adress),
T1.t1Tel = IsNull(T2.t2Tel,T1.t1Tel)
FROM table1 TI
INNER JOIN table2 T2 ON T1.t1ID = T2.t2ID
Try the following select query to check your result 尝试以下选择查询来检查结果
SELECT T1.t1Name,IsNull(T2.t2Name,T1.t1Name),T1.t1Adress,IsNull(T2.t2Adress,T1.t1Adress),T1.t1Tel,IsNull(T2.t2Tel,T1.t1Tel)
FROM table1 TI
INNER JOIN table2 T2 ON T1.t1ID = T2.t2ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.