开发者社区> 问答> 正文

如何通过C#代码部署存储过程?

我有一个类似的存储过程

IF (OBJECT_ID('sp_InsertDevice', 'P') IS NOT NULL) 
    DROP PROCEDURE sp_InsertDevice 
GO

CREATE PROCEDURE sp_InsertDevice
    @serialNumber NVARCHAR(8),
    @modelName NVARCHAR(40),
    @userId INT
AS
BEGIN
    INSERT INTO Device (SerialNumber, ModelName, UserID)
    VALUES (@serialNumber, @modelName, @userId)

    SELECT CAST(SCOPE_IDENTITY() AS INT);
END

和部署它的C#方法:

protected virtual async Task<bool> DeployStoredProcedure(string storedProcedureName)
{
    try
    {
        var dir = Directory.GetFiles(this.StoredProceduresPath);
        string storedProceduresPath = Directory.GetFiles(this.StoredProceduresPath).Where(x => x.Contains(storedProcedureName)).First();
        string storedProcedureScriptFull = File.ReadAllText(storedProceduresPath);

        SqlCommand insertProcedureCommand = new SqlCommand(storedProcedureScriptFull, this.SqlConnection)
                {
                    CommandType = CommandType.Text,
                    CommandTimeout = this.CommandTimeout
                };

        await this.EnsureConnectionOpened();
        await insertProcedureCommand.ExecuteNonQueryAsync();

        return true;
    }
    catch (Exception exception)
    {
        this.SqlConnection.Close();
        ExceptionDispatchInfo.Capture(exception).Throw();
        return false;
    }
}

一般而言,它将存储过程脚本读取为字符串,然后尝试像通常的SQL查询一样执行它。一切正常,直到到达

await insertProcedureCommand.ExecuteNonQueryAsync();

展开
收起
祖安文状元 2020-01-05 14:13:06 551 0
1 条回答
写回答
取消 提交回答
  • 使用动态SQL的解决方法:

    IF (OBJECT_ID('sp_InsertDevice', 'P') IS NOT NULL) 
        DROP PROCEDURE sp_InsertDevice 
    
    EXEC(
    'CREATE PROCEDURE sp_InsertDevice
        @serialNumber nvarchar(8),
        @modelName nvarchar(40),
        @userId int
    AS
    BEGIN
        INSERT INTO Device (SerialNumber, ModelName, UserID)
        VALUES (@serialNumber, @modelName, @userId)
    
        SELECT CAST(SCOPE_IDENTITY() AS INT);
    END');
    
    2020-01-05 14:13:17
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载