我需要根据传递给SQL存储过程的输入条件来过滤表记录, 为简单起见,我使用简单的Employee表(我在项目中使用MSSQL Server)来阐述问题:
tempfile.mktdtemp()
存储过程采用3个输入参数(Id,LastName,Designation)。这将使用至少一个输入参数来调用(其他参数将设置为空字符串(对于LastName,Designation)或0(对于Id))。
这是存储过程,
Table: Employee(Id, FirstName,LastName, Designation)
我认为存储过程中有很多代码重复,请问有人可以提出一种解决这种情况的有效方法吗?
答案 0 :(得分:1)
您可以使用带有WHERE
子句的单个插入查询,该子句涵盖所有逻辑:
BEGIN
INSERT INTO #employees (Id, FirstName, LastName, Designation)
SELECT Id, FirstName, LastName, Designation
FROM Employee
WHERE
(Id = @id AND @id <> 0) OR
(LastName = @lastName AND @lastName <> '') OR
(Designation = @designation AND @designation <> '');
答案 1 :(得分:0)
正如@trincot所说,不需要临时表。我的建议是:
Create Procedure GetEmployees
(
@id int,
@lastName varchar(30),
@designation varchar(30)
)
AS
BEGIN
Select Id, FirstName,LastName,Designation From Employee
Where (@id>'' AND Id = @id)
OR (@lastName>'' AND LastName = @lastName)
OR (@designation>'' AND Designation = @designation);
END
GO