您的位置:首页 > 其它

正确的where in 语句参数化写法

2015-02-08 14:02 127 查看
  相信大家对SQL中的参数化查询并不陌生吧?可是有时候我总是记不住where in 语句的参数化查询方法该怎么写。于是写在这里给自己做个备忘,顺便也提醒一下和我有一样毛病的朋友。

  

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.AccessControl;
using System.Text;

namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
//记得替换成你自己的数据库连接字符串
string connection = "Data Source=(Local);Initial Catalog=;Persist Security Info=True;User ID=sa;PassWord=";
SqlConnection conn = new SqlConnection(connection);
conn.Open();
List<int> lst = new List<int>(){1,3,5};
List<SqlParameter> lstPara = new List<SqlParameter>();
//组合参数查询需要的where in 语句
string cmd = "(";
for (int i = 0; i < lst.Count(); i++)
{
//将参数名添加到字符串中
cmd += "@ID" + (i+1)+",";
//将参数添加到SqlParameter列表中
lstPara.Add(new SqlParameter("@ID"+(i+1),lst[i]));
}
//最后要保证参数字符串是这种形式:(@para1,@para2,@para3,.....)
cmd = cmd.Remove(cmd.Length - 1);
cmd += ")";

SqlCommand command = new SqlCommand("select * from T_Code_Children where vCodeID in"+cmd,conn);
command.Parameters.AddRange(lstPara.ToArray());
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
//在这里下个断点 看一下是否执行成功
conn.Close();
Console.ReadLine();

}
}
}


  顺便说一下,where in(@para) ; @para ="value1,value2,value3,value4....."

  以及

  where in @para ;@para ="(value1,value2,value3,value4......)"

  这两种形式都是行不通的哦。SQL将每个参数作为一个值使用,而不是单纯的作为字符串和Command拼在一起。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: