我有以下代码,我需要替换或追加具有相同名称的字符串。怎么办呢?
我需要使用基于IDNUM的整数追加或替换“ATTRIBUTENAME”列。
CREATE TABLE #STATICFILTER
(
IDNUM INTEGER IDENTITY(1,1),
ATTRIBUTENAME VARCHAR(MAX),
)
Insert into #STATICFILTER
Select * from SPLIT((Select ERSBusinessLogic_Inputs from
ERSBusinessLogic WHERE ERSBusinessLogic_ID =@BusinessID ))
CREATE TABLE #STATICFILTER2
(
IDNUM INTEGER IDENTITY(1,1),
ATTRIBUTENAME VARCHAR(MAX),
STATICID INTEGER
)
Insert into #STATICFILTER2
Select M.ATTRIBUTENAME,SL.ERSStatisticType_ID from #STATICFILTER M
LEFT join [CoSD].[ERSStatisticType_LU] SL
ON M.ATTRIBUTENAME collate SQL_Latin1_General_CP1_CI_AS =
SL.ERSStatisticType_Attribute collate SQL_Latin1_General_CP1_CI_AS
UPDATE #STATICFILTER2
SET ATTRIBUTENAME = ATTRIBUTENAME + CAST(RN AS varchar(1)) FROM
(SELECT ROW_NUMBER() OVER(PARTITION BY ATTRIBUTENAME ORDER
BY IDNUM) AS RN
FROM #STATICFILTER2) AS NEWATTRIBUTENAME
按照以下评论列出一些结果......
#STATICFILTER2 has the below values
IDNUM Attributename Inputvalues
------------------------------------
1 IMPORTS 45
2 IMPORTS 23
3 IMPORTS 28
当我执行上述更新代码时,值将更新为
IDNUM Attributename Inputvalues
------------------------------------
1 IMPORTS1 45
2 IMPORTS1 23
3 IMPORTS1 28
而不是更新为
IDNUM Attributename Inputvalues
------------------------------------
1 IMPORTS1 45
2 IMPORTS2 23
3 IMPORTS3 28
答案 0 :(得分:1)
我不熟悉SQL Server的UPDATE FROM,所以我不知道你的更新语句有什么问题。但您可以使用WITH子句而不是FROM:
来解决它with upd as
(
select s.*, row_number() over (partition by attributename order by idnum) as rn
from #staticfilter s
)
update upd
set attributename = attributename + cast(rn as varchar);
我认为不同之处在于,使用WITH创建包含行号的视图并更新基础表,而使用FROM更新表并使用FROM查找值,因此对于每行评估FROM和结果在第1行,因为它只是你一次看的一行。但这可能是错的;如上所述,我不熟悉这种语法。