1

I Have a sql query as below:

Select CatId 
From tbl_T2H_Category 
Where Category IN ('Category3', 'Category4', 'Category6')

Now what i want is the values inside IN clause should be added dynamically from the checkboxlist. I am getting comma separated values from my control and passing that to the sql query like this:

string mystring = "Category3,Category4,Category6";
cmd.commanText = "Select CatId From tbl_T2H_Category Where Category IN (" + mystring + ")";

This is not executing on sql side, because sql only recognises strings if they are inside "'" "'" (single quotes). Kindly help me write the appropriate query.

4
  • 11
    Step 1, learn about parameterised queries. Commented Jun 11, 2013 at 14:21
  • What version of sql server? Later versions have a better way of handling this. Commented Jun 11, 2013 at 14:22
  • i am using sql server 2008 R2 Commented Jun 11, 2013 at 14:58
  • This looks like an old request for free work, and once people supplied that free work, you did not reply anyway. Please always reply to the people who assist you. Commented Apr 27, 2017 at 11:18

6 Answers 6

6

You want to use a Table-Value Parameter. The MSDN article shown here demonstrates it better than I can:

http://msdn.microsoft.com/en-us/library/bb675163.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for not proposing the obvious, dangerous SELECT 'INJECT' + 'ME' FROM Table
3

This is best dealt with using Table-Valued Parameters.

Your first step is to create the type:

CREATE TYPE dbo.StringList AS TABLE (Value NVARCHAR(MAX) NOT NULL);

Your next step is to create a datatable in c# from your comma separated list to pass to your SqlCommand:

string mystring = "Category3,Category4,Category6";
string[] myarray = mystring.Split(",".ToCharArray());

DataTable table = new DataTable();
table.Columns.Add("Value", typeof(string));

for (int i = 0; i < myarray.Length; i++)
{
    var row = table.NewRow();
    row[0] = myarray[i];
    table.Rows.Add(row);
}

Finally you can pass this to your SqlCommand:

cmd.commanText = "Select CatId From tbl_T2H_Category Where Category IN (SELECT Value FROM @Strings)";
cmd.Parameters.Add(new SqlParameter("@Strings", SqlDbType.Structured)).Value = table;

Comments

2

correct syntax

string mystring = "'Category3','Category4','Category6'";
cmd.commanText = "Select CatId From tbl_T2H_Category Where Category IN (" + mystring + ")";

but please dont use it this was. you can use it like below(but this is not recommended as well)

cmd.commanText = "Select CatId From tbl_T2H_Category Where Category IN ('" + cat_1 + "','" + cat_2 + "','" + cat_3 + "')";

I would use this one below, it is alot secure

string commandText = "Select CatId From tbl_T2H_Category Where Category IN (@cat_1,@cat_2 @cat_3)";
 SqlCommand command = new SqlCommand(commandText, connection);
 command.Parameters.Add("@cat1", SqlDbType.Varchar);
 command.Parameters["@cat1"].Value = "category1";
 command.Parameters.Add("@cat2", SqlDbType.Varchar);
 command.Parameters["@cat2"].Value = "category2";
 command.Parameters.Add("@cat3", SqlDbType.Varchar);
 command.Parameters["@cat3"].Value = "category3";

this last one is much secure, it prevents sql-injection

Comments

0

Just wrap every category in string with single quote?

Something like

var mystring = "'Category3','Category4','Category6'"

2 Comments

This will leave him open to sql injection.
And be sure there is no way, user can forge category values - i.e. if user can submit category with name ';drop table Category;-- you're in trouble
0

Split your comma separated values into an array with

 string[] myArr = commaSepString.Split(',');

and then join them with commas, surrounded by commas like this

 string newString = "'"+myArr.Join("','")+"'";

Comments

0

Try this...

public String returnCategories(string categories) 
    {
        string categoriesConc = "";

        string[] split = categories.Split(',');

        for (int i = 0; i < split.Length; i++) 
        {
            if (string.IsNullOrEmpty(categoriesConc))
            {
                categoriesConc = split[i].ToString();
            }
            else 
            {
                categoriesConc = categoriesConc + "," + split[i].ToString();
            }
        }

        return categoriesConc;
    }

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.