SQL过程 - 使用参数作为运算符

时间:2012-07-31 13:17:16

标签: sql parameters equals operator-keyword procedural

我有一个程序,我试图根据一个高于规定参数的度量值来选择结果。但是,我希望大于等于或小于等的变化。

我试过用>代替对于参数,但它给我错误:     sql语法错误:“PARAM_OP”附近的语法不正确(其中PARAM_OP是应该替换其运算符的参数的名称。

任何想法都会受到欢迎。

以下代码:

var_out = 
SELECT
    "Col1" AS "Col1",
    "Col2" AS "Col2",
    "Col3" AS "Col3",
    SUM(Col4) AS "Col4"

FROM <schema>.<view>
WHERE "Col2" = PARAM_1
GROUP BY Col1, Col2, Col3
HAVING SUM(Col4) > PARAM_2
ORDER BY SUM(Col4);

1 个答案:

答案 0 :(得分:0)

我正在想象类似的东西。

DECLARE @Code VARCHAR(MAX)
SELECT @Code = 
'
var_out = 
SELECT
    "Col1" AS "Col1",
    "Col2" AS "Col2",
    "Col3" AS "Col3",
    SUM(Col4) AS "Col4"
FROM <schema>.<view>
WHERE "Col2" = ' + PARAM_1 + 
'GROUP BY Col1, Col2, Col3
HAVING SUM(Col4) ' + PARAM_OP + ' ' + PARAM_2 
+ 'ORDER BY SUM(Col4);'


EXEC sp_executesql @Code

因此,您构建一个看起来像您想要执行的SQL的字符串,然后使用您的RDBMS提供的任何方式运行SQL字符串。在MSSQL中,这将是sp_executesql