如何在单个语句

时间:2017-07-26 11:53:30

标签: sql sql-server

我想将外键更新到名为用户的表中,其中外键引用项目表,表。 用户属于项目,在组内,该组被定义为项目级别。详细的用户信息也存储在表 ToolUser

User表的create语句如下:

CREATE TABLE [dbo].[User](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [IDproject] [int] NOT NULL,
    [IDtoolUser] [int] NOT NULL,
    [IDgroup] [int] NOT NULL,
    [datemodified] [datetime] NOT NULL DEFAULT (getdate())
  • ID项目项目

  • 中是ID的FK
  • IDtoolUser ToolUser 表格中的ID的FK

  • IDgroup 群组表格中的ID的FK

我想要执行的更新包括更改分配用户所需的组,以解决项目ID,更新用户表中的groupID之前的组ID

我提出了一个解决方案,其中使用函数 [dbo]。[IDofGroup] 计算组ID,并将其用于UPDATE语句,如下所示

UPDATE [dbo].[User] 
SET IDgroup = [dbo].[IDofGroup]('TESTPROJ','none')
FROM [dbo].[User] as u
    INNER JOIN [dbo].[Group] g
        ON g.[ID]= u.[IDgroup] 
    INNER JOIN [dbo].[Project] p 
        ON p.[ID]= u.[IDproject]
        AND p.[name] ='TESTPROJ'
WHERE g.[name] = 'TESTGROUP'
GO

IDofGroup函数本身执行一对SELECT以解析项目ID和组ID,如下所示

ALTER FUNCTION [dbo].[IDofGroup]
(
    -- Add the parameters for the function here
    @ProjectName as varchar(max),
    @GroupName as varchar(max)
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ProjectID int, @ResultID int
    SET @ResultID=0

    -- get project ID for @ProjectName
    SELECT @ProjectID= ID 
    FROM [dbo].[Project] 
    WHERE [name]=@ProjectName

    -- find id fro group which name is @GroupName and project ID @ProjectID
    SELECT @ResultID= ID 
    FROM [dbo].[Group] 
    WHERE [IDproject]=@ProjectID
    AND [name]=@GroupName

    -- Return the result of the function
    RETURN @ResultID

END

我想知道是否有任何方法在单个UPDATE语句中使用某种JOIN执行UPDATE,而不需要在UPDATE语句之前使用函数IDofGroup或其他SELECT语句

1 个答案:

答案 0 :(得分:2)

试试这个:

UPDATE u
SET IDgroup = g1.[ID]
FROM [dbo].[User] as u
    INNER JOIN [dbo].[Project] p 
        ON p.[ID]= u.[IDproject]
    INNER JOIN [dbo].[Group] g
        ON g.[ID]= u.[IDgroup] 
    INNER JOIN [dbo].[Group] g1
        ON g.[IDproject] = g1.[IDproject]
WHERE p.[name] ='TESTPROJ'
AND g.[name] = 'TESTGROUP'
AND g1.[name] = 'none'