我有一个类似的存储过程
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();
使用动态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');
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。