Sql server 若记录在表1中不存在,则更新表2;若记录存在,则使用表1中的列更新表2
我将在Sql server 若记录在表1中不存在,则更新表2;若记录存在,则使用表1中的列更新表2,sql-server,tsql,azure-sql-database,Sql Server,Tsql,Azure Sql Database,我将在T-SQL中的存储过程中执行以下操作 表1包含一些任意的行。表2包含的行数比表1多,但存在的行数相同,只有一列包含日期 如果表1中的一行存在于表2中,我想更新表2的日期列。 如果表2中的一行在表1中不存在,我还想更新表2中的日期列 在我的一生中,我无法理解实现这一点的语法,因为此存储过程不会接受任何参数或输出任何参数。试试这个 update table1 set table1.date = insull(table2.date, getdate()) from table1
T-SQL
中的存储过程中执行以下操作
表1包含一些任意的行。表2包含的行数比表1多,但存在的行数相同,只有一列包含日期
如果表1中的一行存在于表2中,我想更新表2的日期列。
如果表2中的一行在表1中不存在,我还想更新表2中的日期列
在我的一生中,我无法理解实现这一点的语法,因为此存储过程不会接受任何参数或输出任何参数。试试这个
update table1
set table1.date = insull(table2.date, getdate())
from table1
left jion table2
on table2.ID = table1.ID
UPDATE A
SET A.datecol= CASE
WHEN EXISTS (SELECT 1
FROM Table1 B
WHERE B.cola = A.cola) THEN c.Datecol
ELSE getdate()
END
FROM Table2 A
JOIN Table1 C
ON a.cola = c.cola
试试这个
UPDATE A
SET A.datecol= CASE
WHEN EXISTS (SELECT 1
FROM Table1 B
WHERE B.cola = A.cola) THEN c.Datecol
ELSE getdate()
END
FROM Table2 A
JOIN Table1 C
ON a.cola = c.cola
首先,你应该得到不同的表格。检查以下内容:
set nocount on
declare @t1 table (id int, datecolumn datetime)
declare @t2 table (id int, datecolumn datetime, fk_on_t1 int)
declare @diff table(t1_id int, t2_id int)
insert into @diff(t1_id,t2_id)
select
t1.Id
,t2.ID
from @t1 t1
full join @t2 t2 on t1.id = t2.fk_on_t1
现在您可以了解在一个或另一个表中存在哪些行。您可以使用如下查询来更新案例的日期列:
update t2
set datecolumn = getdate()
from @t2 t2
inner join @diff d on d.t2_id = t2.ID
where d.t2_id is not null
通常,您可以只进行一个查询,而不是我的两个查询。选中此项:
update t1
set datecolumn = getdate()
from @t1 t1
full join @t2 t2 on t1.id = t2.fk_on_t1
where t2.ID is not null
首先,你应该得到不同的表格。检查以下内容:
set nocount on
declare @t1 table (id int, datecolumn datetime)
declare @t2 table (id int, datecolumn datetime, fk_on_t1 int)
declare @diff table(t1_id int, t2_id int)
insert into @diff(t1_id,t2_id)
select
t1.Id
,t2.ID
from @t1 t1
full join @t2 t2 on t1.id = t2.fk_on_t1
现在您可以了解在一个或另一个表中存在哪些行。您可以使用如下查询来更新案例的日期列:
update t2
set datecolumn = getdate()
from @t2 t2
inner join @diff d on d.t2_id = t2.ID
where d.t2_id is not null
通常,您可以只进行一个查询,而不是我的两个查询。选中此项:
update t1
set datecolumn = getdate()
from @t1 t1
full join @t2 t2 on t1.id = t2.fk_on_t1
where t2.ID is not null
若记录不存在于表1中,那个么u将以什么值出现并更新table2@Pradeep和它存在的情况相同,只是我将把日期设置为今天的日期,而不是从表1返回的日期。如果记录在表1中不存在,那么u将以什么值进行更新table2@Pradeep就像它存在一样,只有我会将日期设置为今天的日期,而不是从表1返回的日期。谢谢,这正是我想要的!:)你知道我应该读些什么来复习SQL语法吗?我觉得这不必要,很难,我就是不能把我的头绕在它周围。再次感谢你!我在Sql Server 6.5时就知道了,所以没有。从那时起,我就有了文档。谢谢,这正是我要找的!:)你知道我应该读些什么来复习SQL语法吗?我觉得这不必要,很难,我就是不能把我的头绕在它周围。再次感谢你!我从Sql Server 6.5的时候就知道了,所以没有。从那时起,我就有了文档。