0

我有一个如下的 JSON 数组

    [
      {
        "CRT_FIRST_NAME": "abc",
        "CRT_EMAIL": "abc@gmail.com",
        "CRT_ID": 60
      },
      {
        "CRT_FIRST_NAME": "pqr",
        "CRT_EMAIL": "pqr@gmail.com",
        "CRT_ID": 61
      },
      {
        "CRT_FIRST_NAME": "sample",
        "CRT_EMAIL": "sample@gmail.com",
        "CRT_ID": 62
      }
    ]

我正在传递它并执行save_employee_data如下存储过程

 exec save_employee_data '[{"CRT_FIRST_NAME": "abc","CRT_EMAIL": "abc@gmail.com","CRT_ID": 60},{"CRT_FIRST_NAME": "pqr","CRT_EMAIL": "pqr@gmail.com","CRT_ID": 61},{"CRT_FIRST_NAME": "sample","CRT_EMAIL": "sample@gmail.com","CRT_ID": 62}]'

我的存储过程如下

    CREATE PROCEDURE [dfed].[save_employee_data] 
    @jsondata nvarchar(max)
    AS
    DECLARE

    @CRTID_FETCH INT,
    @CRT_FIRST_NAME_FETCH  VARCHAR(250),
    @CRT_EMAIL_FETCH VARCHAR(250)

    BEGIN
        SELECT @CRT_FIRST_NAME_FETCH=CRT_FIRST_NAME, @CRT_EMAIL_FETCH=CRT_EMAIL, @CRTID_FETCH=CRT_ID FROM  
         OPENJSON ( @jsondata )  
        WITH (   
                      CRT_FIRST_NAME   varchar(200) '$.CRT_FIRST_NAME' ,
                      CRT_EMAIL varchar(200) '$.CRT_EMAIL',
                      CRT_ID varchar(200) '$.CRT_ID'
         ) 

        UPDATE employees SET email_staff = @CRT_EMAIL_FETCH WHERE CRT_ID = @CRTID_FETCH
    END

这里更新查询不起作用。我正在尝试循环我的 JSON 数据并从 json 数据中获取CRT_EMAIL, CRT_FIRST_NAME,CRT_ID值,并基于这些值我尝试使用其各自列email_staff的值更新列,CRT_EMAIL即主键CRT_ID

但是更新查询不起作用。这是循环 JSON 数据的正确方法吗?

4

1 回答 1

1

只需将 JSON 数据加入employees表并更新结果。像这样

with n as
(
      SELECT CRT_FIRST_NAME, CRT_EMAIL, CRT_ID 
      FROM OPENJSON ( @jsondata )  
         WITH (   
                CRT_FIRST_NAME   varchar(200) '$.CRT_FIRST_NAME' ,
                CRT_EMAIL varchar(200) '$.CRT_EMAIL',
                CRT_ID varchar(200) '$.CRT_ID'
              ) 
), q as
(
   select n.CRT_EMAIL, e.email_staff , e.crt_id
   from n 
   join employees e
     on n.CRT_ID = e.CRT_ID
)
--select * from q;
update q set email_staff = CRT_EMAIL; 

如果要遍历 json 数据,可以使用游标。例如

DECLARE C CURSOR LOCAL FOR 
    SELECT CRT_FIRST_NAME, CRT_EMAIL, CRT_ID 
    FROM  OPENJSON ( @jsondata )  
    WITH (   
                  CRT_FIRST_NAME   varchar(200) '$.CRT_FIRST_NAME' ,
                  CRT_EMAIL varchar(200) '$.CRT_EMAIL',
                  CRT_ID varchar(200) '$.CRT_ID'
     ); 
OPEN C;

FETCH NEXT FROM C INTO  @CRT_FIRST_NAME, @CRT_EMAIL, @CRT_ID; 
WHILE @@FETCH_STATUS = 0      
BEGIN

    UPDATE employees SET email_staff = @CRT_EMAIL WHERE CRT_ID = @CRT_ID;

    FETCH NEXT FROM C INTO  @CRT_FIRST_NAME, @CRT_EMAIL, @CRT_ID;                 
END

CLOSE C;
DEALLOCATE C;
于 2020-05-26T17:15:54.820 回答