選項與UDF
Declare @YourTable table (ID int,FIX_1 money,FTO int,FIX_2 varchar(max))
Insert Into @YourTable values
(1,null,15452,'1.3-1.7-1.8-2.4-2.0'),
(2,null,15454,'1.4-1.1-1.4-2.7-2.6-1.8-2.4'),
(3,null,15454,'1.9-1.3-1.3')
Update @YourTable Set FIX_1=B.Value
From @YourTable A
Cross Apply (
Select Value = Avg(cast(RetVal as money))
From (Select * from [dbo].[udf-Str-Parse](A.FIX_2,'-')) B1
) B
Select * From @YourTable
選項沒有UDF
Update @YourTable Set FIX_1=B.Value
From @YourTable A
Cross Apply (
Select Value = Avg(cast(RetVal as money))
From (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(A.FIX_2,'-','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B1
) B
雙方將返回
ID FIX_1 FTO FIX_2
1 1.84 15452 1.3-1.7-1.8-2.4-2.0
2 1.9142 15454 1.4-1.1-1.4-2.7-2.6-1.8-2.4
3 1.50 15454 1.9-1.3-1.3
的UDF如果需要
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')
你能告訴你的預期輸出 – TheGameiswar
爲什麼沒有臨時表?如果你不能有臨時表,我假設你不能創建函數? – iamdave
對於id = 1的記錄,FIX_1字段輸出必須爲1.8,對於id = 2的記錄,1.9爲id = 3的記錄爲1.5,對於id爲100的記錄,爲1.6的記錄 –