用于JSON导入的MS SQL存储过程 - 检查输入是否存在

时间:2017-05-05 09:38:32

标签: sql sql-server stored-procedures

我有以下存储过程。

但是如果“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 个答案:

答案 0 :(得分: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;