4

Lets say I have following in my MyScript.Sql file

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.

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. How can I do that? Thanks!

2 Answers 2

5

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:

string value = "Berlin"
script = string.Format(script, value); 

Or, just use the .Replace method:

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:

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();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. It worked in my scenerio. Also, I'd also like to try using Stored Procedure. Can you please share the answer? Thanks again.
Thanks again, that was good to know. I'm using the first solution, since, like you assumed, I need to run .sql file for the scenario.
0

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.

Here is the content of the sql script (note the @pM parameter):

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();
        }


    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.