调用SqlCommandBuilder.DeriveParameters时,存储过程不存在

时间:2014-02-27 19:45:24

标签: c# sql-server stored-procedures

我想从存储过程中获取参数,但是我收到错误

The stored procedure 'Generic.proc_UpdateGenericCatalog' doesn't exist.

命名空间Generic。导致错误,但我不知道我应该使用哪个设置来超越此错误。

- 我的程序 -

ALTER proc [Generic].[proc_UpdateGenericCatalog]
@UserID           UNIQUEIDENTIFIER,
@Name             VARCHAR(30),
@SupplierName     VARCHAR(30),
@SupplierEmail    VARCHAR(50),
@SupplierPhone    VARCHAR(12),
@GenericCatalogID INT
AS

UPDATE [Generic].[GenericCatalog]
      SET [UserID] = @UserID
         ,[Name] = @Name
         ,[SupplierName] =  @SupplierName
         ,[SupplierEmail] = @SupplierEmail
         ,[SupplierPhone] = @SupplierPhone

 WHERE ID = @GenericCatalogID

- 我用来获取参数信息的C#代码 -

- 错误就在这里 SqlCommandBuilder.DeriveParameters(cmd);

我应该如何更改下面的代码,以便获取.DeriveParameter信息?

    private static SqlParameter[] DiscoverParameters(string connectionString, string spName)
    {
         SqlCommand cmd = null;
         SqlParameter[] discoveredParameters = null;
        try
        {
            using (SqlConnection conn = new SqlConnection())
            { 

                conn.ConnectionString = connectionString; 
                conn.Open();

                cmd = new SqlCommand(spName, conn);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlCommandBuilder.DeriveParameters(cmd);
                conn.Close();

                discoveredParameters = new SqlParameter[cmd.Parameters.Count];

                cmd.Parameters.CopyTo(discoveredParameters, 0);

                foreach (SqlParameter discoveredParameter in discoveredParameters)
                {
                    discoveredParameter.Value = DBNull.Value;
                }
                cmd.Dispose();
            }
        }
        catch (Exception) { throw; }
        return discoveredParameters;
    }

1 个答案:

答案 0 :(得分:2)

最可能的解释是,连接字符串中指定的用户无权执行Generic.proc_UpdateGenericCatalog过程。我刚刚在我的一个数据库上测试过,如果用户没有EXEC权限,你将得到“存储过程不存在”错误。

此外,您应该克隆参数,而不是仅仅将它们复制到数组中。这很容易做一些LINQ:

private static SqlParameter[] DiscoverParameters(string connectionString, string spName)
{
    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(spName, connection))
    {
        command.CommandType = CommandType.StoredProcedure;

        connection.Open();
        SqlCommandBuilder.DeriveParameters(command);
        connection.Close();

        return command.Parameters
            .Cast<ICloneable>()
            .Select(p => p.Clone())
            .Cast<SqlParameter>()
            .ToArray();
    }
}