在SQL查询中用值替换条件

时间:2015-03-09 11:17:36

标签: sql-server

我有以下表格

优惠

OfferName OfferRule

Offer 1    Age > 50
Offer 2   City = 'Bangalore' and Age < 10

客户

CustomerName    Age  City       CustomerActive

Customer 1       25   Pune             1   
Customer 2       75   Pune             1  
Customer 1       35   Bangalore        1  

我需要在OfferQuery中使用OfferRule中的值来构建Offer.OfferRule

Select OfferName from Offers where OfferDate > '01 Feb 2015' and 
      Exists(Select Id from Customers where CustomerActive = 1 and 
             Offer.OfferRule)

查询应该被框起并执行为

Select OfferName from Offers where OfferDate > '01 Feb 2015' and 
      Exists(Select Id from Customers where CustomerActive = 1 and 
             City = 'Bangalore' and Age < 10)

Select OfferName from Offers where OfferDate > '01 Feb 2015' and 
      Exists(Select Id from Customers where CustomerActive = 1 and 
             Age > 50)

这可能吗?

1 个答案:

答案 0 :(得分:1)

因此,您可以在表格offers中存储各种优惠,并在offer表格中选择一组规则,并根据客户信息了解哪些优惠符合不同的规则。

也许类似下面的脚本是你正在寻找的东西(或者至少它应该让你知道如何继续)。请注意,它只是作为一个例子 - 可能有更好的方法来实现相同的结果,我没有那么多测试。

下面的脚本会生成如下输出:

Offers with matching customers
------------------------------
Offer 1
Offer 2
Offer 3
Offer 4

剧本:

begin transaction
set nocount on

create table #Offer (OfferName varchar(10), OfferRule varchar(50));
create table #Offers (OfferName varchar(10), offerdate date);
create table #Customers (
    id int, CustomerName varchar(20), Age int, City varchar(20), CustomerActive int);

insert #Offer values 
('Offer 1', 'Age > 50'),
('Offer 2', 'City = ''Bangalore'' and Age < 10'),
('Offer 3', 'Age = 30'),
('Offer 4', 'City = ''Pune''');

insert #Offers values 
('Offer 1', '2015-03-01'),
('Offer 2', '2015-03-01'),
('Offer 3', '2015-03-01'),
('Offer 4', '2015-05-01');

insert #Customers values 
(1, 'Customer 1', 25, 'Pune', 1) ,
(2, 'Customer 2', 75, 'Pune', 1),
(3, 'Customer 3', 35, 'Bangalore', 1),
(4, 'Customer 4',  5, 'Bangalore', 1),
(5, 'Customer 5', 30, 'Bangalore', 1)

declare @stmts table (id int, stmt nvarchar(max), offerrule nvarchar(max))
insert @stmts
select 
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)), 
    N'SELECT OfferName FROM #Offers 
      WHERE OfferDate > ''01 Feb 2015'' 
     AND EXISTS (SELECT Id FROM #Customers WHERE CustomerActive = 1 
     AND ' + offerrule + ') 
     AND OfferName = ''' + OfferName + '''', 
    OfferRule
from #Offer

declare @count int = @@rowcount, @pos int = 1, @stmt nvarchar(max)
declare @results table ("Offers with matching customers" varchar(30))
while (@pos <= @count) 
begin
    select @stmt = stmt from @stmts where id = @pos
    insert into @results exec (@stmt)    
    set @pos += 1
end

select * from @results

rollback transaction