假设我的 MyScript.Sql 文件中有以下内容
declare @city char(10)
set @city = 'Berlin'
If EXISTS( SELECT * FROM Customer where city = @city)
begin
---some stuff to do with the record---
end
使用以下代码,我能够在 .sql 文件之上运行。
string sqlConnectionString = @"MyCS";
FileInfo file = new FileInfo(@"(location of .sql file");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
现在,我希望能够将 @city 的值从我的 C# 代码动态传递到 .sql 脚本,而不是在 .sql 文件本身中设置它的值。我怎样才能做到这一点?谢谢!
最佳答案
我假设您不只是为此使用存储过程而是每次都从文件加载是出于某种原因?如果您要继续调用相同的代码,那确实是这样做的方法,因为您可以将城市作为参数传递。
无论如何,您可以修改 SQL 文件并将“Berlin”替换为“{0}”,然后执行以下操作:
string value = "Berlin"
script = string.Format(script, value);
或者,只需使用 .Replace 方法:
script = script.Replace("Berlin", "New Value");
要将其添加/用作存储过程,您需要在类似于 SQL Server Management Studio 的东西中运行一个脚本,如下所示:
CREATE PROCEDURE AddStuffIfCityExists
@city char(10)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS( SELECT * FROM Customer where city = @city)
BEGIN
--some stuff to do with the record---
END
END
GO
您可以像这样从您的代码中调用它:
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
using (var cmd = new SqlCommand("AddStuffIfCityExists", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@city", "Berlin"));
cmd.ExecuteNonQuery();
}
}
关于c# - 如何使用 C# 运行 .sql 脚本,还需要为 .sql 文件中声明的参数传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25576954/