我有一个SQL Server函数从表中获取nextID。这很简单,但我也想更新表中使用的ID。我正在使用该技术更新到表中,但更新不会发生。代码如下所示,任何人都知道为什么?
CREATE FUNCTION [dbo].[GetNextKeyID]
(
@user nvarchar(10),
@keytype nvarchar(20)
)
RETURNS nvarchar(15)
AS
BEGIN
DECLARE @NextID nvarchar(15);
-- get the next id for this keytype
SELECT @NextID = @user + '_' + @keytype + '_' + CONVERT(VARCHAR(3),
(SELECT CASE WHEN @keytype = 'sess' THEN SessionNext
WHEN @keytype = 'event' THEN EventNext
WHEN @keytype = 'evtc' THEN EventConsultantNext
WHEN @keytype = 'act' THEN ActivityNext
END)
)
FROM dbo.[BARKeys]
WHERE [UserID] = @user
-- increment the next id for this keytype
DECLARE @BARKeys TABLE
(
UserID nvarchar(10),
SessionNext int,
EventNext int,
EventConsultantNext int,
ActivityNext int
)
UPDATE @BARKeys
SET SessionNext = CASE WHEN @keytype ='sess' OR @keytype = 'All'
THEN SessionNext + 1
ELSE SessionNext END
,EventNext = CASE WHEN @keytype ='event' OR @keytype = 'All'
THEN EventNext + 1
ELSE EventNext END
,EventConsultantNext = CASE WHEN @keytype ='evtc' OR @keytype = 'All'
THEN EventConsultantNext + 1
ELSE EventConsultantNext END
,ActivityNext = CASE WHEN @keytype ='act' OR @keytype = 'All'
THEN ActivityNext + 1
ELSE ActivityNext END
WHERE [UserID] = @user
-- return the next id
RETURN @NextID ;
END
答案 0 :(得分:3)
答案 1 :(得分:0)
您无法修改函数内的表数据。
答案 2 :(得分:0)
您似乎正在尝试更新表变量,而不是物理表本身。此外,正如其他人所提到的,您无法在函数中更新物理表的数据。但是,您可以使用存储过程执行此操作。您是否有要求指示需要使用FUNCTION?