我有一个包含varchar(1000)列的 staging 表,其中包含类似
的字符串一些文本\更多文本\文本字符串\又一个字符串\又一个字符串。
记录可以包含\
的8或9次出现,我可以轻松确定
我需要做的是将暂存的记录插入到 * real * 表中,每个字符串都插入到特定的列中。所以我需要确定
如果string包含8个字段,则插入这些目标表列 否则,如果字符串包含9个字段,则插入这些目标表列 否则跳过
我对程序代码很陌生,并且不了解如何实现此 If,Then,Else 逻辑。谁能帮我一把?
答案 0 :(得分:1)
希望此代码可以帮助您解决问题。
create table myTable (
c1 varchar(1024)
, c2 varchar(1024)
, c3 varchar(1024)
, c4 varchar(1024)
, c5 varchar(1024)
, c6 varchar(1024)
, c7 varchar(1024)
, c8 varchar(1024)
, c11 varchar(1024)
, c12 varchar(1024)
, c13 varchar(1024)
, c14 varchar(1024)
, c15 varchar(1024)
, c16 varchar(1024)
, c17 varchar(1024)
, c18 varchar(1024)
, c19 varchar(1024)
);
declare @string as varchar(1024) = 'some text\more text\text string again\still another string\one more string\s6\s7\s8';
declare @col_values as table ( idx int identity(1,1), value varchar(1024) );
declare @row_cnt as integer
-- Split the string into separate values
insert into @col_values
select t.value from string_split (@string,'\') t;
-- Get number of values in splited string
set @row_cnt = @@ROWCOUNT
if @row_cnt = 8
begin
insert into myTable(c1,c2,c3,c4,c5,c6,c7,c8)
values ( (select value from @col_values where idx = 1)
, (select value from @col_values where idx = 2)
, (select value from @col_values where idx = 3)
, (select value from @col_values where idx = 4)
, (select value from @col_values where idx = 5)
, (select value from @col_values where idx = 6)
, (select value from @col_values where idx = 7)
, (select value from @col_values where idx = 8)
);
end;
else
begin
if @row_cnt = 9
begin
insert into myTable(c11,c12,c13,c14,c15,c16,c17,c18,c19)
values ( (select value from @col_values where idx = 1)
, (select value from @col_values where idx = 2)
, (select value from @col_values where idx = 3)
, (select value from @col_values where idx = 4)
, (select value from @col_values where idx = 5)
, (select value from @col_values where idx = 6)
, (select value from @col_values where idx = 7)
, (select value from @col_values where idx = 8)
, (select value from @col_values where idx = 9)
);
end;
else
-- If there is no 8 or 9 values then raise an exception
raiserror(N'Number of elements is %d',16,0,@row_cnt);
end;
select * from myTable ;
drop table myTable ;
go