正确的where in 语句参数化写法
2015-02-08 14:02
127 查看
相信大家对SQL中的参数化查询并不陌生吧?可是有时候我总是记不住where in 语句的参数化查询方法该怎么写。于是写在这里给自己做个备忘,顺便也提醒一下和我有一样毛病的朋友。
顺便说一下,where in(@para) ; @para ="value1,value2,value3,value4....."
以及
where in @para ;@para ="(value1,value2,value3,value4......)"
这两种形式都是行不通的哦。SQL将每个参数作为一个值使用,而不是单纯的作为字符串和Command拼在一起。
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拼在一起。
相关文章推荐
- SAP ABAP 性能优化技巧 — “where” 语句的正确结构
- 宏定义函数指针类型&函数返回左值类值 1。宏定义不分配内存,变量定义分配内存。 2。宏名和参数的括号间不能有空格 3。宏替换只作替换,不做计算,不做表达式求解 //下面是正确的标准的写法 typedef int(FUNC1)(int in); ty
- Select查询数据放一个内表,然后在下一条select语句用where语句in 该内表
- mybatis下oracle查询语句where xxx in(aa,bb)的使用方式
- 不同数据库的参数化SQL语句的写法
- .net sql where in 参数化
- CodeIgniter $this->db->where()的自定义语句写法问题
- oracle mysql sql serve where in 语句的不同
- SqlServer Update更新语句因where条件不正确 造成更新全表的情况
- 关于sql条件语句where id in (@参数)执行报错问题(转换成数据类型 int 时失败)(
- 代码编写注意_(IIF,SQL语句的WHERE条件写法)
- 优化mysql中where or和where in语句的效率
- [Hibernate框架]Hql语句in中带参数的写法
- Flex Query语句中where的写法示例
- .net sql where in 参数化
- C# 参数化SQL语句中的like和in
- MySQL的WHERE语句中BETWEEN与IN的使用教程
- 优化mysql中where or和where in语句的效率
- 对传入where条件的sql语句进行参数化处理
- mapper.xml中SQL语句in的写法