我正在尝试执行更新和选择...基本上,根据索引进行更新,然后选择已更新的行ID。
使用OUTPUT子句很简单:
UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id
WHERE Baz = 2
但现在,我如何将其变为变量?
DECLARE @id INT
这三个不起作用:
UPDATE Foo
SET Bar = 1
OUTPUT @id = INSERTED.Id
WHERE Baz = 2
SET @id =
(UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id
WHERE Baz = 2)
SET @id =
(SELECT Id FROM (UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id Id
WHERE Baz = 2) z)
最后一个包括在内,因为当管理工作室中的所有红色波浪线消失时,它让我暂时兴奋。唉,我收到这个错误:
A nested INSERT, UPDATE, DELETE, or MERGE statement is not allowed in a SELECT statement that is not the immediate source of rows for an INSERT statement.
答案 0 :(得分:83)
由于更新可能会影响多行,因此需要一个表来存储其结果:
declare @ids table (id int);
UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id INTO @ids
WHERE Baz = 2
如果您确定只有一行会受到影响,您可以提取ID:
declare @id int
select top 1 @id = id
from @ids
答案 1 :(得分:65)
如果只有一行受到影响,则可以在没有表变量的情况下完成。
DECLARE @id INT
UPDATE Foo
SET Bar = 1, @id = id
WHERE Baz = 2
SELECT @id
答案 2 :(得分:2)
或者,如果只有一行受到影响:
import org.springframework.security.acls.domain.BasePermission;
public class MyPermission extends BasePermission { //use this class for creating custom permissions
private static Map<String, Integer> customPerMap = new HashMap<String, Integer>();
static {
customPerMap.put("READ", 1);
customPerMap.put("WRITE", 2);
customPerMap.put("DELETE", 4);
customPerMap.put("PUT", 8);
}
/**
*Use the function while saving/ getting permission code
**/
public static Integer getCode(String permName) {
return customPerMap.get(permName.toUpperCase());
}