[英]How to run .sql script using C#, also need to pass values for parameters that are declared in .sql file?
Lets say I have following in my MyScript.Sql file假设我在 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
using following code, i'm able to run above .sql file.使用以下代码,我可以在 .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();
Now, I want to be able to dynamically pass the value of @city from my C# code to the .sql script instead of setting it's value in .sql file itself.现在,我希望能够将@city 的值从我的 C# 代码动态传递到 .sql 脚本,而不是在 .sql 文件本身中设置它的值。 How can I do that?
我怎样才能做到这一点? Thanks!
谢谢!
I'm assuming there is some reason you're not just using a stored procedure for this and instead loading this from a file each time?我假设有某种原因你不只是为此使用存储过程,而是每次都从文件中加载它? That's really the way to do this if you're going to keep calling the same bit of code since you can pass the city as a parameter.
如果您要继续调用相同的代码,那么这确实是这样做的方法,因为您可以将城市作为参数传递。
Anyway, you could just modify the SQL file and replace 'Berlin' with '{0}', then just do this:无论如何,您可以修改 SQL 文件并将“柏林”替换为“{0}”,然后执行以下操作:
string value = "Berlin"
script = string.Format(script, value);
Or, just use the .Replace method:或者,只需使用 .Replace 方法:
script = script.Replace("Berlin", "New Value");
To add/use it as a stored procedure, you'd run a script in something like SQL Server Management Studio that looks like this:要将其添加/用作存储过程,您需要在类似 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
You can call it from your code like this:您可以像这样从代码中调用它:
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();
}
}
Here is how I got it to work.这是我如何让它工作的。 I have the SQL statement in a file, then have a WinForm that prompts the user for a value, runs the SQL and renders the results.
我在一个文件中有 SQL 语句,然后有一个 WinForm 提示用户输入一个值,运行 SQL 并呈现结果。
Here is the content of the sql script (note the @pM parameter):下面是sql脚本的内容(注意@pM参数):
SELECT
[computerName]
,[principleName]
,[appStarted]
,[appEnded]
,[appStatus]
,[appExecName]
,[appPID]
FROM
[dbo].[AppActivity]
WHERE
[principleName] LIKE '%' + @pM + '%' AND
[appStatus] = 'ACTIVE'
Here is the class:这是课程:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Printing
{
public partial class RunDBScript : Form
{
DataTable Dt = new DataTable();
string strITSupportDB = Properties.Settings.Default.ITSupportDB;
string strActiveAppSessions = Properties.Settings.Default.ActiveAppSessions;
string SQLString;
public RunDBScript()
{
InitializeComponent();
FileInfo file = new FileInfo(@strActiveAppSessions);
SQLString = file.OpenText().ReadToEnd();
}
private void RunDBScript_Load(object sender, EventArgs e)
{
}
private void btnGetActiveSessions_Click(object sender, EventArgs e)
{
btnGetActiveSessions.Visible = false;
try { Dt.Clear(); } catch { };
try
{
using (SqlConnection connection = new SqlConnection(strITSupportDB))
{
connection.Open();
SqlCommand command = new SqlCommand(SQLString, connection);
command.Parameters.Add("@pM", SqlDbType.NVarChar);
command.Parameters["@pM"].Value = txtUserName.Text.Trim();
SqlDataReader Dr = command.ExecuteReader();
Dt.Load(Dr);
}
}
catch(Exception ex) { MessageBox.Show(ex.GetBaseException().ToString().Trim(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
if(Dt.Rows.Count > 0) { dgvActiveSessions.DataSource = Dt; } else { dgvActiveSessions.DataSource = null; };
btnGetActiveSessions.Visible = true;
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.