[英]sql query: select all users where timeMade was more than hoursNeeded
[英]select query where clause with more than 1 value
我有一列名为ast_code
的列
我已经检索到一个string
变量。 我试图基于存储在该变量中的字符串值使用where
子句运行select
查询。
这是我尝试的代码:
public void grid()
{
datatable dt = new datatable();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
try
{
command.Connection = myConnection;
command.CommandText = "SELECT code, name from table.menu where code <> '"+ ast_code + "'";
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Fill(dt);
myConnection.Open();
}
catch(Exception ex)
{
MessageBox.Show("error" + ex);
}
myConnection.Close();
gridControl1.DataSource = dt;
}
当我运行查询时,除非字符串变量中的值仅包含一个值(例如0110300
),否则它不会返回任何结果。
然后,我尝试转换变量的内容:
ast_code = a.Replace(';',',').Replace(' ','\'');
但由于缺少'
,返回了错误。 不介意a
; 这是一个解析变量值。 我已经尝试将它们存储到list
但是也不能正常工作。
我需要做的是生成一个可以处理多个值的where
子句。
更新
iam使用@ rbr94建议ast_code = a.Replace("; ", "', '");
command.CommandText = "SELECT code, name from table.menu where code not in '"+ ast_code + "'";
错误地在where子句中设置'
导致出现错误。 我举一个例子:
您有一个像这样的字符串: 0110300; 0110370
0110300; 0110370
然后使用ast_code = a.Replace(';',',').Replace(' ','\\'');
结果是: 0110300,'0110370
。 当您在where子句中使用此代码时,很明显这是行不通的:
where code <> '0110300,'0110370'
首先,使用WHERE NOT IN
,然后您需要执行以下操作:
C#:
ast_code = string.Format("'{0}'", a.Replace("; ","', '"));
SQL:
where code NOT IN (" + ast_code + ")
//results in
where code NOT IN ('0110300','0110370')
这将在您的ast_code
字符串之前和之后设置'
。 然后,您替换;
以及其后的空格以'; '
'; '
以便每个值的两边都带有'
标记。
结果为: '0110300', '0110370'
我认为您必须像这样在声明中使用NOT IN
:
command.CommandText = "SELECT code, name from table.menu where code NOT IN ('" + ast_code.Replace(";", "','") + "')";
因此,我对自己的问题的解决方案是,首先iam将其拆分以存储在list<>
所以iam仅直接存储ast_code = a
然后我用来存储的代码
string[] code_asst = ast_code.Split(';');
List<string> clean_code_asst = new List<string>();
foreach (string s in code_asst)
{
clean_code_asst.Add("'"+s.Trim()+"'");
}
string types = string.Join(",", clean_code_asst.ToArray());
我使用的查询是
var sql = "Select code from table.menu where code NOT IN ("+types+")";
command.CommandText = sql;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.