How do I create a stored procedure that will optionally search columns?(如何创建可以选择搜索列的存储过程?)
问题描述
我正在开发一个工作应用程序,它将查询我们的员工数据库.最终用户希望能够根据标准姓名/部门条件进行搜索,但他们还希望能够灵活地查询在卫生部门工作、名字为James"的所有人员.我想避免的一件事是简单地让存储过程获取参数列表并生成要执行的 SQL 语句,因为这会在内部级别打开 SQL 注入的大门.
I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.
这能做到吗?
推荐答案
虽然 COALESCE
技巧很巧妙,但我更喜欢的方法是:
While the COALESCE
trick is neat, my preferred method is:
CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry
@Cus_Name varchar(30) = NULL
,@Cus_City varchar(30) = NULL
,@Cus_Country varchar(30) = NULL
,@Dept_ID int = NULL
,@Dept_ID_partial varchar(10) = NULL
AS
SELECT Cus_Name
,Cus_City
,Cus_Country
,Dept_ID
FROM Customers
WHERE (@Cus_Name IS NULL OR Cus_Name LIKE '%' + @Cus_Name + '%')
AND (@Cus_City IS NULL OR Cus_City LIKE '%' + @Cus_City + '%')
AND (@Cus_Country IS NULL OR Cus_Country LIKE '%' + @Cus_Country + '%')
AND (@Dept_ID IS NULL OR Dept_ID = @DeptID)
AND (@Dept_ID_partial IS NULL OR CONVERT(varchar, Dept_ID) LIKE '%' + @Dept_ID_partial + '%')
这些类型的 SP 可以很容易地生成代码(并为表更改重新生成).
These kind of SPs can easily be code generated (and re-generated for table-changes).
您有几个处理数字的选项 - 取决于您想要精确语义还是搜索语义.
You have a few options for handling numbers - depending if you want exact semantics or search semantics.
这篇关于如何创建可以选择搜索列的存储过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何创建可以选择搜索列的存储过程?


基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01