Stored Procedure with optional quot;WHEREquot; parameters(带有可选“WHERE的存储过程参数)
问题描述
我有一个表单,用户可以在其中指定各种参数来挖掘一些数据(状态、日期等).
I have a form where users can specify various parameters to dig through some data (status, date etc.).
我可以生成一个查询:
SELECT * FROM table WHERE:
status_id = 3
date = <some date>
other_parameter = <value>
等等.每个 WHERE
都是可选的(我可以选择 status = 3
的所有行,或 date = 10/10/1980
的所有行,或 status = 3 AND date = 10/10/1980
等的所有行).
etc. Each WHERE
is optional (I can select all the rows with status = 3
, or all the rows with date = 10/10/1980
, or all the rows with status = 3 AND date = 10/10/1980
etc.).
给定大量参数,都是可选的,构成动态存储过程的最佳方法是什么?
Given a large number of parameters, all optional, what is the best way to make up a dynamic stored procedure?
我正在处理各种数据库,例如:MySQL、Oracle 和 SQLServer.
I'm working on various DB, such as: MySQL, Oracle and SQLServer.
推荐答案
最简单的方法之一:
SELECT * FROM table
WHERE ((@status_id is null) or (status_id = @status_id))
and ((@date is null) or ([date] = @date))
and ((@other_parameter is null) or (other_parameter = @other_parameter))
等等.这完全消除了动态 sql 并允许您搜索一个或多个字段.通过消除动态 sql,您消除了关于 sql 注入的另一个安全问题.
etc. This completely eliminates dynamic sql and allows you to search on one or more fields. By eliminating dynamic sql you remove yet another security concern regarding sql injection.
这篇关于带有可选“WHERE"的存储过程参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有可选“WHERE"的存储过程参数


基础教程推荐
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01