当操作数可变时,T-SQL中有什么方法可以使用动态操作数?

时间:2019-08-12 22:27:09

标签: sql-server-2016

我试图允许用户在自定义警报应用程序中选择操作数。但是,由于可以设置许多不同版本的警报,并且它们都可以同时运行,因此我无法创建变量来保存操作数,而仍将其作为基于集合的操作来运行(至少我无法弄清楚,因此这篇文章)。

通过一系列操作,我最终得到了一个像这样的数据集:

  BusinessISN | InvoiceID | InvoiceTotal | Measure | ThresholdValue 
 -------------|-----------|--------------|---------|---------------- 
    100002550 |   1165803 |       1171.8 | =       |        1616.96 
    100002315 |   1165804 |         3190 | >=      |           3000 
    100002550 |   1165806 |       473.68 | =       |        1616.96 
    100003156 |   1165807 |         1612 | <=      |           2000 
    100002550 |   1165809 |      1616.96 | =       |        1616.96 
    100002550 |   1165810 |       1760.8 | =       |        1616.96 
              |           |              |         |                

我想做的是能够使用Measure中调用的操作数将Invoicetotal与ThresholdValue进行比较。

我提前道歉,我无法弄清楚应该如何格式化数据。我尝试创建一个HTML表,但即使这样似乎也不起作用。

1 个答案:

答案 0 :(得分:0)

我不确定自己想要的结果是什么,但是可以使用一些动态SQL来完成。

我假设您要获取记录的BusinessISNInvoiceID,其中条件在其他三列(InvoiceTotalMeasure和{{ 1}})的计算结果为true-这就是我写的。

首先,创建并填充示例表(在您将来的问题中为我们保存此步骤):

ThresholdValue

然后,将DECLARE @T AS TABLE ( BusinessISN int, InvoiceID int, InvoiceTotal float, Measure varchar(2), ThresholdValue float ) INSERT INTO @T (BusinessISN, InvoiceID, InvoiceTotal, Measure, ThresholdValue) VALUES (100002550, 1165803, 1171.8, '= ', 1616.96), (100002315, 1165804, 3190, '>=', 3000), (100002550, 1165806, 473.68, '= ', 1616.96), (100003156, 1165807, 1612, '<=', 2000), (100002550, 1165809, 1616.96, '= ', 1616.96), (100002550, 1165810, 1760.8, '= ', 1616.96); for xml一起使用以动态生成stuff查询:

union all

接下来,手动检查您使用DECLARE @Sql nvarchar(max); SELECT @Sql = STUFF ( ( SELECT N' UNION ALL SELECT '+ CAST(BusinessISN as nvarchar(11)) + N' AS BusinessISN, '+ CAST(InvoiceID as nvarchar(11)) + N' AS InvoiceID '+ N'WHERE '+ CAST(InvoiceTotal as varchar(100)) +' '+ Measure +' '+ CAST(ThresholdValue as varchar(100)) FROM @T FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 10, '') 创建的SQL。在处理动态SQL时,print命令是您最好的朋友。

print

打印内容应能为您提供以下输出,尽管其组织性稍差(基于示例数据):

PRINT @Sql

然后,当您确定已正确查询时,只需执行该查询即可:

SELECT 100002550 AS BusinessISN, 1165803 AS InvoiceID WHERE 1171.8 =  1616.96 UNION ALL 
SELECT 100002315 AS BusinessISN, 1165804 AS InvoiceID WHERE 3190 >= 3000 UNION ALL 
SELECT 100002550 AS BusinessISN, 1165806 AS InvoiceID WHERE 473.68 =  1616.96 UNION ALL 
SELECT 100003156 AS BusinessISN, 1165807 AS InvoiceID WHERE 1612 <= 2000 UNION ALL 
SELECT 100002550 AS BusinessISN, 1165809 AS InvoiceID WHERE 1616.96 =  1616.96 UNION ALL 
SELECT 100002550 AS BusinessISN, 1165810 AS InvoiceID WHERE 1760.8 =  1616.96    

应该给您以下结果:

EXEC(@Sql)

You can see a live demo on rextester.