遍历表ID列,将其传递给URL(JSON),插入表中?

时间:2019-03-17 11:17:33

标签: sql sql-server tsql

我认为我会为此使用光标。我理解这个概念,但绝不花太多时间将其付诸实践。我的任务是通过Swagger通过API将数据提取到SQL Server。

如果我声明@branch变量,则代码在下面可以正常工作,但是我很懒惰,因为我将代码复制了17次并更改了@branch变量,就像我将其插入表一样例如,当新的分支机构加入时,自动化未来的流程

我有一个名为dbo.branches的表,看起来像这样:

branch_example

上面提到的最有效的代码是

DECLARE @Object AS INT;
DECLARE @hr AS INT

DECLARE @json AS TABLE (Json_Table NVARCHAR(MAX))
DECLARE @URL AS NVARCHAR(MAX)
DECLARE @branch AS NVARCHAR(MAX)
DECLARE @shortname AS NVARCHAR(MAX)
DECLARE @api_key AS NVARCHAR(MAX)

DECLARE @start_date AS DATE
DECLARE @offset AS INT
DECLARE @count AS INT

SET @api_key = '123456'
SET @shortname = 'abcd'
SET @branch = '0004-888c'
SET @offset = 0
SET @start_date = convert(char(10),getdate()-90,126)
SET @count = 1000
SET @URL= CONCAT('https://*************/',@shortname,'/********?branchID=',@branch,'&startDate=',@start_date,'&offset=',@offset,'&count=',@count,'&api_key=',@api_key)

Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',@URL,'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

INSERT INTO @json (Json_Table) 
   EXEC sp_OAGetProperty @Object, 'responseText'

SELECT * FROM @json

INSERT INTO dbo.mortgages
    SELECT * 
    FROM OPENJSON((select * from @json), N'$.Data')
    WITH 
        ([Amount] DECIMAL(8,2) N'$.Amount',
         [Borrower_Account_Name] NVARCHAR(MAX) N'$.BorrowerAccountName',
         [Created_At] DATETIME2 N'$.CreatedAt',
         [Extra_Notes] NVARCHAR(MAX) N'$.ExtraNotes',
         [Interest_Rate] NVARCHAR(MAX) N'$.IntrestRate',
         [Market_Value] DECIMAL(8,2) N'$.MarketValue',
         [Monthly_Payment] DECIMAL(5,2) N'$.MonthlyPayment',
         [Mortgage_Account_Number] NVARCHAR(MAX) N'$.MortgageAccountNumber',
         [Mortgage_Provider] NVARCHAR(100)  N'$.MortgageProvider',
         [Property_Ownable_ID] NVARCHAR(MAX) N'$.PropertyOwnableID',
         [Sales_Instruction_ID] NVARCHAR(5) N'$.SalesInstructionID',
         [Type] NVARCHAR(MAX) N'$.Type',
         [Valuation_Date] DATETIME2  N'$.ValuationDate'
    )   

我想实现的是dbo.branches的OID传递到@branch,后者将完成@URL,循环循环,将dbo.branches中每个OID的JSON输出插入dbo.mortgages < / p>

我在颅骨中也曾在dbo.branches中需要一个row_number,因此当它遍历时知道何时停止?

非常感谢您的帮助!

0 个答案:

没有答案