日期:2014-05-18  浏览次数:20480 次

能否在一条SQL里完成更新和取数据两个事情?
想在一条语句里完成对一个值的更新和获取,比如先加1再SELECT出来,怎么写?

------解决方案--------------------
一条语句不可能 ,但可以放一个事务里面
------解决方案--------------------
SQL code
DECLARE @T TABLE (COL1 INT)
INSERT INTO @T
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
UPDATE T1 SET COL1=COL1+1
OUTPUT DELETED.COL1 AS COL1_OLD,INSERTED.COL1 AS COL1_NEW
FROM @T T1
WHERE COL1<3
/*
COL1_OLD    COL1_NEW
----------- -----------
1           2
2           3
*/

------解决方案--------------------
SQL code
create table tb
(
   id int,name varchar(10)
)
insert into tb
select 1,'aa'


declare @t table(name1 varchar(10),name2 varchar(10))
update tb
set name='bb'
output inserted.name,deleted.name into @t
where id=1

select * from @t
/*
------
name1    name2