This question already has answers here:
Multiple Id's in In clause of SQL Query C# [closed]
(2 answers)
Parameterize an SQL IN clause
(41 answers)
How to add parameter in SELECT query for fieldName IN #fieldName construction [duplicate]
(3 answers)
Closed 4 years ago.
I have a problem with calling by SQL Server database. I have this table
and an object with property Groups, which is something like "all nj sk2".
My query in ssms is
SELECT *
FROM Hours
WHERE class_id = 1
AND groups IN ('all', 'nj', 'sk2')
In C# I'm doing something like this
var query = "SELECT * FROM Hours WHERE class_id = #class_id AND groups LIKE (#groups)";
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#class_id", User.Current.ClassId);
cmd.Parameters.AddWithValue("#groups", User.Current.Groups.Replace(" ", ", "));
}
The only way I made this work was
var groups = "('" + User.Current.Groups.Replace(" ", "', '").Remove(User.Current.Groups.Length - 2);
//above is ('all', 'nj', 'sk2')
var query = "SELECT * FROM Hours WHERE class_id = #class_id AND groups LIKE " + groups;
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#class_id", User.Current.ClassId);
}
But this is not a good solution imo, so if anyone knows what am I doing wrong please help me out. Thanks
Related
This question already has answers here:
Pass Array Parameter in SqlCommand
(11 answers)
Closed 5 months ago.
I have a specific question about the WHERE IN command inside of a parameterized sql query.
Current situation
All the normal queries are working, but on the following query example it goes wrong:
SELECT * FROM table WHERE Id IN(#Ids)
What does this query do?
This query is selecting all items in the table with the specific ids.
The error
# this generates the following string: "1,2,3,4", which gets parsed into the #Ids param
new OleDbParameter("Ids", String.Join(",", objects.Select(c => c.Id.ToString())));
This will generate the folling raw sql query:
# this is the converted sql query after performing the OleDbCommand.ExecuteNonQueryAsync()
# which is not working
SELECT * FROM table WHERE Id IN("1,2,3,4")
# this is the sql query that is working
SELECT * FROM table where Id IN("1", "2", "3", "4")
solution
as you can see, the first example is an array, but is not an array inside of the IN statement. How can I change my code so it will get the working sql query with parameterization?
You could try this
var ids = new char[objects.Count()];
Array.ForEach(ids, x => x = '?');
var idsList = string.Join(',', ids);
var queryString = $"SELECT * FROM table WHERE Id IN ({idsList})";
var command = new OleDbCommand(queryString, connection);
for (int i = 0; i < ids.Length; i++)
{
command.Parameters.Add($"#p{i + 1}", OleDbType.VarChar, 5).Value = objects.ElementAt(i).Id;
}
OleDbDataReader reader = command.ExecuteReader();
This question already has answers here:
A table name as a variable
(10 answers)
Closed 1 year ago.
I am building a sql query string like this:
var sqlDailyDataForOption = #"select underlying_symbol, quote_date
FROM [#val6]
Later I add the command line parameters thus:
command.Parameters.AddWithValue("#val6", o.underlying_symbol + "_1545");
I get an exception when I try to execute the query string:
using (SqlDataReader reader = command.ExecuteReader())
{
- $exception {"Invalid object name '#val6'."} System.Data.SqlClient.SqlException
However, if I hardwire the value o.underlying_symbol + "_1545" it works fine.
Is it that command-parameters can't be dynamically created in a FROM ?
You would have to use dynamic SQL and safely inject the value of the dynamic object into the statement. I'm not a C# developer, but I suspect it'll look something like this:
var sqlDailyDataForOption = #"DECLARE #SQL nvarchar(MAX) = N'SELECT underlying_symbol, quote_date FROM dbo.' + QUOTENAME(#var6) + N';'; EXEC sys.sp_executesql #SQL;"
command.Parameters.Add("#Var6", SqlDbType.NVarChar, 128).Value = o.underlying_symbol + "_1545"
try this
var val16=o.underlying_symbol + "_1545";
var sqlDailyDataForOption = $"select underlying_symbol, quote_date FROM [{val16}]";
but please remember about possibility sql script injection attack in this case and check val16 for malicious words like delete.
This question already has answers here:
Pass Array Parameter in SqlCommand
(11 answers)
Parameterize an SQL IN clause
(41 answers)
Closed 4 years ago.
I have a List<int> whose values I want to use inside IN() clause in my query.
I have read many similar post but none of them worked for me yet.
Let's say my table T is:
Id1 (int) | Id2(int)
Query:
Select Id1
From T
where Id2 in (5,7,9,11)
List:
List<int> ls = new List<int>();
ls.add(5);
ls.add(7);
ls.add(9);
ls.add(11);
Now, how to populate this list in my query as no of integers?
Tried so far:
1)
string ls = string.Join(",", Id2.ToArray());
string getId1 = "select Id1 from T where Id2 in (#ls)";
cmd = new SqlCommand(getId1, con);
cmd.Parameters.Add(new SqlParameter("#ls", ls));
Error:
Conversion failed when converting the nvarchar value '5,7,9,11' to
data type int.
2)
var ls = "("
+ String.Join(",", Id2.Select(x => x.ToString()).ToArray())
+ ")";
string getId1 = "select Id1 from T where Id2 in (#ls)";
cmd = new SqlCommand(getId1, con);
cmd.Parameters.Add(new SqlParameter("#ls", ls));
Error:
Conversion failed when converting the nvarchar value '(5,7,9,11)' to
data type int.
Note : I'll prefer the answer without using LINQ unless it's only possible with LINQ
List<int> ls = new List<int>();
ls.Add(5);
ls.Add(7);
ls.Add(9);
ls.Add(11);
string sql = string.Format( "select Id1 from T where Id2 in ({0})", string.Join(",",ls.Select(n=> "#prm"+n).ToArray()));
SqlCommand cmd = new SqlCommand(sql);
foreach(int n in ls){
cmd.Parameters.AddWithValue("#prm"+n, n);
}
This question already has answers here:
How to add line break in C# behind page
(11 answers)
Closed 8 years ago.
I have this line :
cmd.CommandText = "SELECT registeruser_id,registeruser_username, registeruser_email,registeruser_password FROM TestDB_RegisterUser where registeruser_email='" + email + "' and registeruser_password='" + pwd + "' and registeruser_rowstate<3 ";
And when I try to hit Enter on part of the string , I get a big bunch of red lines that indicates that what I did is considered as error .
How do I break it then ? thanks
Yes, because a regular string literal can't include a line break in the source code. You can include one in a verbatim string literal however:
string sql = #"SELECT FOO
FROM BAR
WHERE X=Y";
Or break it with string concatenation:
string sql = "SELECT FOO " +
"FROM BAR " +
"WHERE X=Y";
More importantly, however, you're currently building your SQL in a horribly insecure way. Never include values directly in the SQL like this. Instead, use parameterized SQL and then specify values for the parameters:
string sql = "SELECT FOO FROM BAR WHERE X=#X";
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#X", SqlDbType.NVarChar).Value = "...";
using (var reader = command.ExecuteReader())
{
...
}
}
This question already has answers here:
SqlCommand read one value
(2 answers)
Closed 9 years ago.
I'm fetching date from the database and following is my command for it:
SqlCommand cmd = new SqlCommand("select dob from sample Where cardnum = '" + TextBox1.Text + "'");
How do i save the output of this command into datetime?
At the simplest:
var when = (DateTime)cmd.ExecuteScalar();
However, in the more general case you woulnd need to know about readers and parameters. Or: use a tool like dapper:
var when = conn.Query<DateTime>(
"select dob from sample Where cardnum = #num",
new { num = TextBox1.Text } // parameters, done right
).Single();
But dapper will read entire objects too (mapping properties to columns), not just single values.