sql server 2008中带插入和更新的CTE
我正在使用SQL Server 2008,我想知道是否可以将CTE与insert和update一起使用,例如,如果一个条件失败,则插入else updatesql server 2008中带插入和更新的CTE,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我正在使用SQL Server 2008,我想知道是否可以将CTE与insert和update一起使用,例如,如果一个条件失败,则插入else update With X As ( Select COMP From comp ) IF EXISTS ( Select * From A Where A.COMP = X.COMP ) Insert Into A (COMP,comp1) select X.COMP, @COMP1 from X Else U
With X As
(
Select COMP
From comp
)
IF EXISTS ( Select * From A Where A.COMP = X.COMP )
Insert Into A (COMP,comp1)
select X.COMP, @COMP1 from X
Else
Update A set comp1=@comp1
where comp= X.Comp
我试着用
With X As
(
Select COMP
From comp
)
Insert Into A (COMP,comp1)
select X.COMP, @COMP1 from X
With Y As
(
Select COMP
From comp
)
Update A set comp1=@comp1
join Y on comp= Y.Comp
但是如果它是一个insert,那么它就是在插入记录,同时它也在执行更新块。您能告诉我如何使用If语句避免这种情况吗。由于声明CTE后只能使用一次,所以不能在INSERT和UPDATE语句中使用它 正如您所说,由于约束超出您的控制范围,您无法使用合并,因此可以使用临时表:
Select COMP
into #temp
From comp
IF EXISTS ( Select * From A Where A.COMP = #temp.COMP )
Insert Into A (COMP,comp1)
select #temp.COMP, @COMP1 from #temp
Else
Update A set comp1=@comp1 where comp= #temp.Comp
WITH子句只能与单个SELECT、INSERT、UPDATE或DELETE语句一起使用。它不能与IF或任何其他语句一起使用。你已经在评论中被告知了 第二次尝试(尝试对INSERT和UPDATE使用SELECT WITH子句)失败的原因可能是INSERT语句末尾没有分号。with关键字在Transact-SQL中有多个用途,有时它在语句的中间,而在其他时候则是在开始时。为了避免歧义,如果下一条语句以with子句开头,SQL Server 2008及更高版本将在语句末尾强制使用分号 但事实上,这将是一场灾难 因此,这是您应该如何同时运行这两条语句:
With X As
(
Select COMP
From comp
)
Insert Into A (COMP,comp1)
select X.COMP, @COMP1 from X; /* <-- this semicolon is required */
With Y As
(
Select COMP
From comp
)
Update A set comp1=@comp1
join Y on comp= Y.Comp; /* <-- this one is optional,
but why not make things consistent? */
你自己也试过吗?去吧!您可能想签入MERGE命令-不,我不想使用MERGE。是的,我已经尝试过了,但出现了错误。如果我的密码错了,请告诉我。如果我能那样写,你的代码是错的。除非使用merge,否则不能在同一语句中执行insert和update。CTE仅在一个语句中可用。