在存储过程中使用DYNAMIC sql的CASE语句

时间:2017-07-13 16:57:27

标签: sql sql-server stored-procedures sql-server-2012 sql-server-2016

我试图通过将Dynamic SQL存储在存储过程中的变量中来构建CASE WHEN语句,但是我收到以下错误。有人可以分享您对如何解决此错误的看法。谢谢。

- 代码

SELECT
             CASE WHEN  ResultTableName LIKE '%Loss_ByEvent]'
                  THEN  @SQLStmt =
                        N'CREATE TABLE dbo.' + ResultTableName + N' (
                        ' + CreateStmt + N'
                        ) ON Loss_ByAnalysis(SliceID)'                    
                  WHEN  ResultTableName LIKE '%Loss_ByGeo]'
                  THEN  @SQLStmt =
                        N'CREATE TABLE dbo.' + ResultTableName + N' (
                        ' + CreateStmt + N'
                        ) ON Loss_ByAnalysis(SliceID)'                    
                  ELSE 
                  @SQLStmt =
                        N'CREATE TABLE dbo.' + ResultTableName + N' (
                        ' + CreateStmt + N'
                        )'
              END
            ,@DBName = DBName
            ,@ResultTableName = ResultTableName
        FROM #CreateResult_ResultTables lr
        WHERE ID = @ResultTableCount;

- 错误: -

Msg 102, Level 15, State 1, Procedure Procedure_name, Line 141 [Batch Start Line 7]
Incorrect syntax near '='.

enter image description here

2 个答案:

答案 0 :(得分:2)

您收到错误,因为CASE是SQL中的函数,但您正在使用它,就好像它是一个语句或列形式。

SELECT
     @SQLStmt =
         CASE WHEN  ResultTableName LIKE '%Loss_ByEvent]'
              THEN  N'CREATE TABLE dbo.' + ResultTableName + N' (
                    ' + CreateStmt + N'
                    ) ON Loss_ByAnalysis(SliceID)'                    
              WHEN  ResultTableName LIKE '%Loss_ByGeo]'
              THEN  N'CREATE TABLE dbo.' + ResultTableName + N' (
                    ' + CreateStmt + N'
                    ) ON Loss_ByAnalysis(SliceID)'                    
              ELSE 
                    N'CREATE TABLE dbo.' + ResultTableName + N' (
                    ' + CreateStmt + N'
                    )'
          END
        ,@DBName = DBName
        ,@ResultTableName = ResultTableName
    FROM #CreateResult_ResultTables lr
    WHERE ID = @ResultTableCount;

@SeanLange是正确的,非常易受SQL注入攻击。

答案 1 :(得分:0)

你有没有尝试过这种方式

var obj = {"Item1":{"title":"demo1","uuid":"2ecc82ba-4e47-4a8d-90ff-c4beb4148255"},"Item2":{"title":"demo3","uuid":"10b216d4-d354-42b9-8c53-f6bb9e8f0079"}}
var old = {"Item1":{"title":"demo1","uuid":"2ecc82ba-4e47-4a8d-90ff-c4beb4148255"},"Item2":{"title":"demo2","uuid":"fbe9bfbf-1c61-45bb-94d0-2983328a5e74"}}

var newKeys = Object.keys(obj).map(e => obj[e].uuid)
var oldKeys = Object.keys(old).map(e => old[e].uuid)

var result = newKeys.filter(e => !oldKeys.includes(e));
console.log(result)