Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove last comma from query C#

Tags:

c#

asp.net

I am doing something as follows..

querybuilder = ("SELECT Type, Text FROM [Element] WHERE Id IN( ");
foreach (var item in CaseIdList)
{
   querybuilder += item + ",";
}
querybuilder += ")";

at the last insdie the closing bracket I am getting a comma. How to remove that.

like image 878
Rocky Avatar asked Aug 02 '12 05:08

Rocky


People also ask

How do you remove the last comma?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!

How do I remove the last comma in SQL?

First, you want to TRIM your data to get rid of leading and trailing spaces. Then REVERSE it and check if the first character is , . If it is, remove it, otherwise do nothing. Then REVERSE it back again.


5 Answers

use TrimEnd(','); to remove last comma from the string, string.TrimEnd

After the foreach loop use:

querbuilder = querybuilder.TrimEnd(',');

Instead of concatenating string, you may use StringBuilder class.

like image 154
Habib Avatar answered Oct 14 '22 21:10

Habib


Firstly, I'd try to avoid including the values themselves directly. Use parameters where possible - it's less simple for IN(x, y, z) style parameters, but you can either use a table-valued parameter or simply dynamically create the parameter list (e.g. to IN(@p0, @p1, @p2))

Secondly, I'd avoid using string concatenation in a loop - use StringBuilder if you really have to loop round.

Thirdly, I'd use string.Join to avoid having to loop at all:

string commaSeparated = string.Join(", ", values);
like image 27
Jon Skeet Avatar answered Oct 14 '22 22:10

Jon Skeet


Instead of the foreach-loop u can use the string.Join method. Take a look at this

like image 23
Tomtom Avatar answered Oct 14 '22 21:10

Tomtom


You can use String.Join(",", item); This means there is no ugly trimming or splitting that you have to do.

like image 27
Pieter Germishuys Avatar answered Oct 14 '22 21:10

Pieter Germishuys


I would use String.Join:

querybuilder = "SELECT Type, Text FROM [Element] WHERE Id IN( " + String.Join(",", CaseIdList.ToArray()) + ")";

I would also look into using Parameters instead of constructing SQL with strong concatenation - string concatenation is vulnerable to SQL injection attacks, and parameters are easy to use.

How you would switch to parameters depends on how you're accessing the database, and which database engine, but a quick google search should help.

like image 31
TheEvilPenguin Avatar answered Oct 14 '22 20:10

TheEvilPenguin