参数化一个简单的SQL更新查询

时间:2017-03-01 20:48:55

标签: sql-server tsql

我有以下代码作为SQL中的存储过程但它不接受@DBNAME声明它需要声明但我已经声明了它。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE UpdateSQL
-- Add the parameters for the stored procedure here
@UpdateField varchar(25),
@UpdateValue varchar(25),
@FilterField varchar(25),
@FilterValue varchar(25),
@DBNAME sysname

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
UPDATE @DBNAME SET @UpdateField = @UpdateValue WHERE @FilterField = @FilterValue
END
GO

这是调用SQL过程的c#函数:

internal static bool UpdateSql(SqlArgs pSqlArgs)
{
    var pwd = GetPwd();
    var sqlCred = new SqlCredential(Sqluser, pwd);

    var tCatalog = GetDbo(pSqlArgs.PCatalog);

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

    var sqlCommand = new SqlCommand
    {
        Connection = sqlConnection,
        CommandText = "UpdateSQL",
        Parameters = { new SqlParameter("@DB", pSqlArgs.PDbo), new SqlParameter("@UpdateField", pSqlArgs.PUpdateField),
            new SqlParameter("@UpdateValue", pSqlArgs.PUpdateValue), new SqlParameter("@FilterField", pSqlArgs.PFilterField),
            new SqlParameter("@FilterValue", pSqlArgs.PFilterValue) },
            CommandType = CommandType.StoredProcedure,
    };


    try
    {
        sqlConnection.Open();

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

我正在尝试运行的最终功能是:USE @Database UPDATE @Table SET @UpdateField = @UpdateValue WHERE @FilterField = @FilterValue

2 个答案:

答案 0 :(得分:2)

您需要使用动态SQL,因为您无法在查询中将表名或列名指定为参数:

{{1}}

GO

答案 1 :(得分:0)

您的代码将@DBNAME声明为sysname,但update语句需要一个表。

我想你可能想看一下这篇文章:how to set table name in dynamic sql query?

此外,这篇文章还讨论了同样的问题:How should I pass a table name into a stored proc?