sqlserver stored procedure traverses the dataset


foreword

Today, a maintenance project found that the data imported into the question bank by excel would be repeated. It was found that the sql needs to be modified. First insert the question table to obtain the question id, and then insert the four options into the option table to associate the question.

Using the code for loop to repeatedly link to the database to insert questions and options feels very frustrating. It should be better to write a stored procedure...


1. Stored procedure

The previous logic was to first upload the question bank excel in the background, save the data in the temporary topic and option table,
and then click OK to upload the temporary table data to the official topic and option table
. After 2 hours, let me get it done, ok!

Probably pass in a stored procedure with parameters, use the cursor to traverse the temporary topic table found, add it to the official topic table, use [@@IDENTITY] to get the newly added primary key id, and add the corresponding topic option with parameter
storage process


create proc jkc_examImport @guid NVARCHAR(200)

AS
DECLARE
    @subject_id AS INT,
    @tmp_subject_id AS INT,
    @subject_title AS NVARCHAR(10),
    @subject_type AS  INT,
    @question_bank_id AS INT,
    @subject_resole AS NVARCHAR(4000);
    
-- 声明游标
DECLARE C_subject CURSOR FAST_FORWARD FOR
    SELECT subject_id,subject_title,subject_type,question_bank_id,subject_resole 
    FROM jkc_tsp_subject_temp
    where guid=@guid ;
    
OPEN C_subject;

-- 取第一条记录
FETCH NEXT FROM C_subject INTO @tmp_subject_id,@subject_title,@subject_type,@question_bank_id,@subject_resole;

WHILE @@FETCH_STATUS=0
BEGIN
    -- 操作
	 insert into jkc_tsp_subject(subject_title,subject_type,question_bank_id,subject_resole) values(@subject_title,@subject_type,@question_bank_id,@subject_resole);
	 set @subject_id=@@IDENTITY;

	 insert into jkc_tsp_sub_option(subject_id,option_sign,option_content,is_correct) select @subject_id as subject_id,option_sign,option_content,is_correct from jkc_tsp_sub_option_temp where subject_id=@tmp_subject_id;

    -- 取下一条记录
    FETCH NEXT FROM C_subject INTO @tmp_subject_id,@subject_title,@subject_type,@question_bank_id,@subject_resole;
END

-- 关闭游标
CLOSE C_subject;

-- 释放游标
DEALLOCATE C_subject;



c# calling code

//执行下方sql语句
EXEC jkc_examImport '2bab2070-b0db-464c-8e63-e034fdf6d406'

Summarize

A lot of things are not used, they will really be lost

Guess you like

Origin blog.csdn.net/lyk520dtf/article/details/126732242