2017-04-20 18 views
2

目前在存儲過程中硬編碼的業務規則有很多。希望探索設置規則表的選項,我們打算在其中鍵入所有業務規則並基於它執行存儲過程。如何在sql服務器中建立規則表

雖然系統很複雜,但在這裏提供了一個簡單的版本。

Create table tblTest 
(
    TranID int primary key not null, 
    FName varchar(20) not null, 
    Age int not null, 
    Salary money not null, 
    MaritalStatus char(1) not null 
) 

Insert into tblTest values (1, 'Alex', 26, '25000.00','Y') 
Insert into tblTest values (2, 'Brenda', 25, '14500.00','Y') 
Insert into tblTest values (3, 'Peter', 69, '50000.00','N') 
Insert into tblTest values (4, 'Paul', 64, '74500.00','Y') 

我們保持示例簡單讓我們假設業務規則是以下: 1.年齡> = 25,
2.年齡< 65和
3.薪酬> 15K

Create table tblBusRule 
(
    RuleID int Primary key not null, 
    ColName varchar(20) not null, 
    Operator varchar(2) not null, 
    ColValue varchar(10) not null, 
    RuleOrder int not null 
) 

Insert into tblBusRule values (1, 'Age', '>=', '25', 1) 
Insert into tblBusRule values (2, 'Age', '<', '65', 2) 
Insert into tblBusRule values (3, 'Salary', '>', '15000.00', 3) 

直接查詢會是這樣的,它會單獨輸出記錄1(Alex)和4(Paul)。

Select * from tblTest 
where 
     age >=25 and 
     age < 65 and 
     salary > '15000.00' 

現在如何使這個動態基於tblBusRule中提到的規則?

回答

1

使用stuff() with select ... for xml path ('') method of string concatenationsp_executesql

declare @sql nvarchar(max), @where nvarchar(max); 
set @where = stuff((
    select ' and '+colname +' '+operator +' ' + colvalue+char(10) 
    from tblBusRule 
    order by RuleOrder 
    for xml path (''), type).value('.','nvarchar(max)') 
    ,1,6,''); 

set @sql = 'select * ' +char(10)+'from tblTest'+char(10)+'where '[email protected]; 

select @sql as CodeGenerated; 
exec sp_executesql @sql; 

rextester演示:http://rextester.com/CGRF91788

回報:

+-------------------------+ 
|  CodeGenerated  | 
+-------------------------+ 
| select *    | 
| from tblTest   | 
| where Age >= 25   | 
| and Age < 65   | 
| and Salary > 15000.00 | 
+-------------------------+ 

+--------+-------+-----+------------+---------------+ 
| TranID | FName | Age | Salary | MaritalStatus | 
+--------+-------+-----+------------+---------------+ 
|  1 | Alex | 26 | 25000,0000 | Y    | 
|  4 | Paul | 64 | 74500,0000 | Y    | 
+--------+-------+-----+------------+---------------+ 

參考: - The curse and blessings of dynamic SQL - Erland Sommarskog

+0

謝謝您的回答。試圖瞭解我們如何能夠制定這個業務規則表。如果必須針對不同的表應用規則,腳本將如何更改。我的意思是假設薪金欄在表B中。 – prasanth

+0

@prasanth。 。 。那麼它可以像你投入的工作一樣靈活......如果你想讓規則適用於多個表,那麼你應該確定哪些規則適用於哪些表,並檢索適用於表的規則在你的查詢中。 – SqlZim

+0

:)好吧,也許會發布它作爲一個單獨的問題與示例結構和輸出預計會得到更清晰。謝謝。 – prasanth

相關問題