Michael
Michael

Reputation: 305

Pass parameters to Stored Procedure with single quotes

I am using the below code to execute a Stored Procedure. But the problem is the string strGroup is a hardcoded value and I need to pass the string in single quotes and when I run this the SP is not getting executed.

CODE:

 protected void Page_Load(object sender, EventArgs e)
    {
        string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(CS);
        SqlCommand command = new SqlCommand();
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataTable dt = new DataTable();  
        string strGroup = "'Sub Group'";
        try
        {
            connection.Open();
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "SP_Code";
            command.Parameters.AddWithValue("@Group",strGroup);
            adapter = new SqlDataAdapter(command);
            adapter.Fill(dt);

            var query = from r in dt.AsEnumerable()
                        where r.Field<string>("Organization") == "Nestle"
                        select new
                        {
                            Department = r["Department "].ToString(),
                            Group = r["L2 Group"].ToString(),
                            Code = r["Code"].ToString()                               
                        };
            GridView1.DataSource = query;
            GridView1.DataBind();                        
    }

If I execute the SP in SQL server with passing parameters it works perfectly and not sure if I am doing something wrong when passing the string in single quotes. Can someone assist me when I am making mistake.

Upvotes: 2

Views: 2280

Answers (1)

Sefa
Sefa

Reputation: 8992

There is no need for quotes when you are sending your variable as parameter. In some scenarios people write sql queries and execute them. For example, if you write this query in your code, you will need to add single quotes

var name = "Sefa";
var query = string.Format("INSERT INTO [People](Name) VALUES('{0}')",name);

But when you are doing it via SqlCommand class, you can send the variable as it is. So, just remove the single quotes.

Upvotes: 1

Related Questions