参数化SQL插入失败

时间:2017-03-02 19:50:09

标签: c# sql sql-server parameterized

我有一个c#winform应用程序,我正在尝试将我的insert语句转换为参数化的sql存储过程。当我执行非执行时,我回到-1,我似乎无法找出原因。

SQL过程:

CREATE PROCEDURE CreateReceiver
-- Add the parameters for the stored procedure here
@DBNAME sysname,
@SiteID varchar(25),
@Receiver varchar(25),
@StatusID int,
@ExpDelDate Date,
@CreateDate DateTime,
@CreateUserID varchar(25),
@CreateUserName varchar(25),
@ModDate DateTime,
@ModUserName varchar(25),
@ModUserID varchar(25),
@UserField5 varchar(25)
AS
BEGIN

DECLARE @sql NVARCHAR(MAX);

SET @sql = '
INSERT INTO @DBNAME (SiteId, ReceiverNumber, StatusId, ExpectedDeliveryDate, CreatedDate, CreatedUserID, 
CreatedUserName, ModifiedDate, ModifiedUserID, ModifiedUserName, UserField5) VALUES (@SiteID,@Receiver,@StatusID,
@ExpDelDate,@CreateDate,@CreateUserID,@CreateUserName,@ModDate,@ModUserID,@ModUserName,@UserField5)
';
SET @sql = REPLACE(@sql, '@DBNAME', @DBNAME);

exec sp_executesql @sql,
                   N'@SiteID varchar(25), @Receiver varchar(25), @StatusID int, @ExpDelDate Date, @CreateDate DateTime, @CreateUserID varchar(25),
                    @CreateUserName varchar(25), @ModDate DateTime, @ModUserID varchar(25), @ModUserName varchar(25), @UserField5 varchar(25)',
                   @SiteID=@SiteID, @Receiver=@Receiver, @StatusID=@StatusID, @ExpDelDate=@ExpDelDate, @CreateDate=@CreateDate, 
                   @CreateUserID=@CreateUserID, @CreateUserName=@CreateUserName, @ModDate=@ModDate, @ModUserID=@ModUserID, 
                   @ModUserName=@ModUserName, @UserField5=@UserField5;
END
GO

以下是调用该过程的c#代码:

internal static bool BuildReturnReceiver(string pReturnTrackingNumber, string pCustomer, string pSiteId, SqlArgs pSqlArgs)
    {
        var pwd = GetPwd();
        var sqlCred = new SqlCredential(Sqluser, pwd);
        var tCatalog = GetDB(pSqlArgs.sqlDB);

        var sqlConnection = new SqlConnection
        {
            ConnectionString = $"Data Source={SqlServer};Initial Catalog=TSC-Telaid;",
            Credential = sqlCred
        };

        var dbName = $"[{tCatalog}].dbo.[{pSqlArgs.sqlTable}]";

        var tExpDelDate = CalculateDays();
        var name = GetUser();

        var sqlCommand = new SqlCommand
        {
            Connection = sqlConnection,
            CommandType = CommandType.StoredProcedure,
            CommandText = "CreateReceiver",
            Parameters = { new SqlParameter("@DBNAME", dbName), new SqlParameter("@SiteID", pSiteId),
                new SqlParameter("@Receiver", pSqlArgs.sqlFilterValue), new SqlParameter("@StatusID", 56), new SqlParameter("@ExpDelDate", tExpDelDate),
                new SqlParameter("@CreateDate", DateTime.Now), new SqlParameter("@CreateUserID", WindowsIdentity.GetCurrent().Name),
                new SqlParameter("@CreateUserName", name), new SqlParameter("@ModDate", DateTime.Now), new SqlParameter("@ModUserID", WindowsIdentity.GetCurrent().Name),
                new SqlParameter("@ModUserName", name), new SqlParameter("@UserField5", pSqlArgs.sqlUpdateValue)},
        };

        try
        {
            sqlConnection.Open();
            return sqlCommand.ExecuteNonQuery().Equals(1);
        }
        catch (SqlException ex)
        {
            MessageBox.Show(@"Error: " + ex.Message, @"Exception", MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation);
            return false;
        }
        finally
        {
            sqlConnection.Close();
        }

    }

- 编辑 -

更正了SQL过程:

Alter PROCEDURE CreateReceiver
-- Add the parameters for the stored procedure here
@DBNAME sysname,
@SiteID varchar(MAX),
@Receiver varchar(MAX),
@StatusID int,
@ExpDelDate Date,
@CreateDate DateTime,
@CreateUserID varchar(MAX),
@CreateUserName varchar(MAX),
@ModDate DateTime,
@ModUserName varchar(MAX),
@ModUserID varchar(MAX),
@UserField5 varchar(MAX)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);

SET @sql = N'
INSERT INTO ' + @DBNAME + '(SiteId, ReceiverNumber, StatusId, ExpectedDeliveryDate, CreatedDate, CreatedUserID, 
CreatedUserName, ModifiedDate, ModifiedUserID, ModifiedUserName, UserField5) VALUES (@SiteID,@Receiver,@StatusID,
@ExpDelDate,@CreateDate,@CreateUserID,@CreateUserName,@ModDate,@ModUserID,@ModUserName,@UserField5)
';
--SET @sql = REPLACE(@sql, '@DBNAME', @DBNAME);

exec sp_executesql @sql,
                   N'@SiteID varchar(MAX), @Receiver varchar(MAX), @StatusID int, @ExpDelDate Date, @CreateDate DateTime, @CreateUserID varchar(MAX),
                    @CreateUserName varchar(MAX), @ModDate DateTime, @ModUserID varchar(MAX), @ModUserName varchar(MAX), @UserField5 varchar(MAX)',
                   @SiteID=@SiteID, @Receiver=@Receiver, @StatusID=@StatusID, @ExpDelDate=@ExpDelDate, @CreateDate=@CreateDate, 
                   @CreateUserID=@CreateUserID, @CreateUserName=@CreateUserName, @ModDate=@ModDate, @ModUserID=@ModUserID, 
                   @ModUserName=@ModUserName, @UserField5=@UserField5;
END
GO

1 个答案:

答案 0 :(得分:0)

您不能将表名作为参数传递(在这种情况下,它名为@DBNAME)。

您需要制作查询的那一部分。注意我还在字符串的开头添加了N.这是为了避免从ASCII转换到UNICODE的任何陷阱。

SELECT CASE WHEN EXISTS (SELECT 1 FROM ( SELECT TOP 1 RequestID FROM tT 
                                         UNION 
                                         SELECT TOP 1 RequestID FROM tET
                                         UNION 
                                         SELECT TOP 1 RequestID FROM tE 
                                       ) AS idSearcher 
                                       WHERE idSearcher.RequestID = 120
                        ) 
            THEN 'y' ELSE 'n' END AS alreadyHasID

- 编辑 -

删除了QUOTENAME感谢SqlZim,他指出您将Database.schema.TableName作为单个数据传递。周围的QUOTENAME无法解决问题。