SQL / VBA INSERT问题

时间:2014-11-26 16:37:42

标签: sql sql-server excel vba excel-vba

我正在尝试创建用户列表,具体取决于谁使用我的Excel电子表格。

当用户打开工作簿时,打开的脚本会下载用户列表,检查该用户是否存在以及是否将其添加到用户列表。

现在我可以使用存储过程下载用户详细信息,但是只要我在其中添加一行来检查用户是否存在,如果没有添加用户,VBA就会抛出一个错误,声称“当时不允许操作”对象已关闭'

VBA代码:

Sub UserDL()
Dim us As Worksheet
Dim USArr(0 To 11) As Variant
Dim sKey As String

Application.ScreenUpdating = False

With UserList
    .RemoveAll
    .CompareMode = vbTextCompare
End With

ThisUser = Environ("userdomain") & "\" & Environ("username")

Call ConnecttoDB

Set Cmd = New ADODB.Command: Set rs = New ADODB.Recordset

With Cmd
    .CommandTimeout = 30
    .ActiveConnection = cn
    .CommandText = "CSLL.DLUsers"
    .CommandType = adCmdStoredProc
    .Parameters("@Alias").Value = Environ("userdomain") & "\" & Environ("username")

    Set rs = .Execute
End With

With rs     
    If Not .BOF And Not .EOF Then
        .MoveLast
        .MoveFirst
        While (Not .EOF)
            On Error Resume Next
            If (IsNull(rs("FirstName")) Or IsNull(rs("LastName"))) = True Then
                Call AliasDet(rs("Alias"))
            End If
            On Error GoTo 0
            For i = 1 To 11
                USArr(i - 1) = rs(i)
            Next i
                With UserList
                    sKey = rs("Alias")
                    If Not .Exists(sKey) Then
                        .Add sKey, USArr
                    End If
                End With
            .MoveNext
        Wend
    End If
End With

Set Cmd = Nothing: Set rs = Nothing
End Sub

SQL存储过程:

    @Alias as varchar(max)
AS

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

SELECT * FROM [CSLL].[Users]

任何人都可以帮助解决为什么它在用户不存在时抛出错误(如果用户确实存在它运行正常,所以我希望它与SQL存储过程有关,但无法看到哪里)

1 个答案:

答案 0 :(得分:0)

这可能是由尝试从存储过程返回值的INSERT语句引起的。尝试将SET NOCOUNT ON;放在存储过程的顶部,以防止返回受影响的记录计数:

[SP Header and Parameters]
AS
SET NOCOUNT ON; -- Prevent insert from returning a result.

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

SELECT * FROM [CSLL].[Users]