过程:
将sTexture值(表1)按顿号分割,按分割后的字符串在表2中查找出sTextureId,合并后给sTextureId赋上(表1)。
这里我们将sTexture值为分割时命名为0str(0次分割时的字符串,也就是总共的字符串)、11str(一次分割后第一个字符串)、12str(一次分割后第二个字符串)、21str、22str,4个主要变量; 所以没有顿号时的字符串为0str,有一个顿号时的字符串为11str和12str,有两个顿号时的字符串为11str、21str和22str。第一个顿号的位置命名为1dot,余下以此类推。
T-sql:
--声明计数器
declare @i int
set @i=1
declare @0str char(50)
declare @0strLength int
--Crop表中记录的行数
declare @rows int
select @rows=count(*) from Crop
--第一个顿号的位置
declare @1dot int
--利用循环完成所有行的更新
while (@i<=@rows)
begin
--查出未分割时记录值(这里均指sTexture的值)
select @0str=sTexture from Crop where cropId=@i
--求出记录值的长度
set @0strLength=len(@0str)
--求出第一个顿号的位置,若没顿号则返回0
set @1dot=patindex('%、%',@0str)
--如果不存在逗号,则查出记录值对应的id(指sTextureId,下同)并在Crop中更新
if @1dot=0
declare @0strId char
select @0strId =soilTextureId from GiSoilTexture where soilTextureName=@0str
begin
update Crop set sTextureId=@0strId where cropId=@i
end
--如果存在逗号,则开始分割
else if @1dot !=0
--第一次分割后第一个字符串
declare @11str char(50)
--第一次分割后第二个字符串
declare @12str char(50)
--第二个顿号在12str中的位置
declare @2dot int
--求出11str的值
set @11str= substring(@0str,1,(@1dot-1))
--求出12str的值
set @12str= substring(@0str,(@1dot+1),(@0strLength-@1dot))
--求出第二个顿号在12str中的位置
set @2dot =patindex('%、%',@12str)
--11str的id
declare @11strId char
--查询出11str的id
select @11strId =soilTextureId from GiSoilTexture where soilTextureName=@11str
begin
--如果第二个顿号不存在则将11strId、12strId合并更新到Crop表中
if @2dot =0
begin
--12str的id
declare @12strId char
--查询出12str的id
select @12strId =soilTextureId from GiSoilTexture where soilTextureName=@12str
--更新sTextureId(只有一个逗号时)
update Crop set sTextureId=(@11strId+@12strId) where cropId=@i
end
--如果第二个逗号存在,则开始第二次分割
else if @2dot!=0
begin
declare @21str char(50)
declare @22str char(50)
--21str的id
declare @21strId char
--22str的id
declare @22strId char
--12str的长度
declare @12strLength int
set @12strLength =len(@12str)
--求出21str的值
set @21str = substring(@12str,1,(@2dot -1))
--求出22str值
set @22str = substring(@12str,(@2dot+1),(@1dot-1))
--查询她们的id
select @21strId =soilTextureId from GiSoilTexture where soilTextureName=@21str
select @22strId =soilTextureId from GiSoilTexture where soilTextureName=@22str
--更新(有两个个逗号时)
update Crop set sTextureId=(@11strId+@21strId+@22strId) where cropId=@i
end
end
set @i=@i+1
end
更新后抓图:

表3
问题:
结果都正确,但有一个错误提示:
