2017-05-05 69 views
0

我有以下存儲過程。JSON導入的MS SQL存儲過程 - 檢查輸入是否存在

但是,如果「X-Forwarded-For」爲空,我想檢索「remote_address」。

我該怎麼做?

CREATE PROCEDURE dbo.Table(@payload NVARCHAR(MAX)) 
WITH ENCRYPTION 
AS  
    SET NOCOUNT ON; 
    IF (ISJSON(@payload) != 1) THROW 50001, 'JSON data expected', 1; 

    INSERT INTO dbo.Table(IP,Time) 
    SELECT JSONData.IP, getdate() 
    FROM OPENJSON (@payload) 
      WITH ( 
       IP  varchar(50) N'$.request.headers."X-Forwarded-For"' 
      ) 
    AS JSONData; 
GO 

遠程地址的行看起來像:

   IP  varchar(50) N'$.transaction.remote_address' 

回答

1
SELECT COALESCE(JSONData.XForwardedForIP, JSONData.RemoteAddressIP), getdate() 
FROM OPENJSON (@payload) 
     WITH ( 
      XForwardedForIP varchar(50) N'$.request.headers."X-Forwarded-For"', 
      RemoteAddressIP varchar(50) N'$.transaction.remote_address' 
     ) 
AS JSONData; 
+0

哦!我喜歡這樣的表情:D我只是在外面吃午飯,所以今天下午考試。謝謝! – Marcus