select query where子句的值超过1

时间:2016-11-16 09:20:31

标签: c# sql winforms

我有一个名为FROM frolvlad/alpine-oraclejdk8:slim VOLUME /tmp ADD gs-spring-boot-docker-0.1.0.jar app.jar RUN sh -c 'touch /app.jar' ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -jar /app.jar" ]

的列

enter image description here

我已经检索到docker run -e "JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y" -p 8080:8080 -p 8000:8000 -t springio/gs-spring-boot-docker 变量。我正在尝试使用ast_code子句根据我存储在该变量中的字符串值运行string查询。

这是我尝试过的代码:

select

当我运行查询时,它没有返回任何结果,除非字符串变量中的值只包含一个值(例如where)。

然后我尝试转换变量的内容:

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子句。

更新

我使用@ rbr94建议list

where

当iam使用top ast_code = a.Replace("; ", "', '");时它会起作用,但对于第二行`string值给我一个错误 enter image description here enter image description here

3 个答案:

答案 0 :(得分:2)

错误地在where子句中设置'会导致错误。我举个例子:

你有一个这样的字符串: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'

答案 1 :(得分:0)

我认为你必须在你的陈述中使用NOT IN,如下所示:

command.CommandText = "SELECT code, name from table.menu where code NOT IN ('" + ast_code.Replace(";", "','") + "')";

答案 2 :(得分:0)

所以,我对自己问题的解决方案是首先将它拆分为存储在list<>中 所以我只是直接存储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;