SQL存储过程检查是否存在然后添加。如果不更新

时间:2015-02-25 14:23:36

标签: sql sql-server vba stored-procedures

我正在尝试编写一个存储过程来填充用户表(命名为CSLL.Users)

触发时,程序会给出一系列用户详细信息。

然后检查表中是否存在别名。如果不是,则添加别名。然后sp继续填充其余列(使用更新命令)

使用vba调用它,但在调用时抛出错误。我认为这是第一个IF NOT EXISTS声明,但看不出我可能出错的地方。

ALTER procedure [CSLL].[UploadUser]
    -- Add the parameters for the stored procedure here
    @Name varchar(max) = NULL,
    @FirstName varchar(max) = NULL,
    @LastName varchar(max) = NULL,
    @Email varchar(max) = NULL,
    @Telephone varchar(max) = NULL,
    @Division varchar(max) = NULL,
    @Manager varchar(max) = NULL,
    @DirectReports varchar(max) = NULL,
    @Title varchar(max) = NULL
AS

SET NOCOUNT ON

IF NOT EXISTS(SELECT 1 FROM [CSLL].[Users] Where [Alias] = @Name) INSERT INTO [CSLL.Users] ([Alias], [Country], [Role]) VALUES (@Name, 'UK', 'Employee')

UPDATE [CSLL].[Users]
    SET FirstName = @FirstName,
        LastName = @LastName,
        Email = @Email,
        Telephone = @Telephone,
        Division = @Division,
        Manager = @Manager,
        DirectReports = @DirectReports,
        Title = @Title
WHERE Alias = @Name

DECLARE @Pos int
DECLARE @DR varchar(max)

SET @DirectReports = @DirectReports + ','

WHILE LEN(@DirectReports) > 0
    BEGIN

    SET @Pos = CHARINDEX(',', @DirectReports, 1)

    SET @DR = (CASE @Pos
        WHEN 0 THEN RTRIM(LTRIM(@DirectReports))
        ELSE RTRIM(LTRIM(LEFT(@DirectReports, @Pos - 1)))
    END)

    IF NOT EXISTS(SELECT 1 FROM [CSLL].[Users] where [Alias] = @DR) INSERT INTO [CSLL].[Users] ([Alias], [Country], [Role]) VALUES (@DR, 'UK', 'Employee')

    SET @DirectReports = RIGHT(@DirectReports, LEN(@DirectReports) - @Pos)
    END

1 个答案:

答案 0 :(得分:1)

这似乎是由一个错字造成的:

-- you currently use: [CSLL.Users]
IF NOT EXISTS(SELECT 1 FROM [CSLL].[Users] WHERE [Alias] = @Name) 
    INSERT INTO [CSLL.Users] ([Alias], [Country], [Role]) 
    VALUES (@Name, 'UK', 'Employee')

而是尝试:

-- use: [CSLL].[Users]
IF NOT EXISTS(SELECT 1 FROM [CSLL].[Users] Where [Alias] = @Name) 
    INSERT INTO [CSLL].[Users] ([Alias], [Country], [Role]) 
    VALUES (@Name, 'UK', 'Employee')