在这种特殊情况下,如何进行相关更新?

时间:2018-10-16 15:50:13

标签: sql database tsql sql-update union

我遇到了问题。

If Object_Id('abc','U') is not null
    Drop table  abc
Go
Create Table abc
(
    Strng varchar(max)

)
GO
Insert abc
Select 'shakuntala'
Union All
Select 'shakuntala-anjna'
Union All
Select 'shakuntala-anjna-sharat'
GO
Create Table def
(
    Strng varchar(max),
    Initcap varchar(max)
)
GO
Insert def
Select 'shakuntala', 'Shakuntala'
Union All
Select 'shakuntala-anjna','Anjna'
Union ALl
Select 'shakuntala-anjna','Shakuntala'
Union All
Select 'shakuntala-anjna-sharat', 'Anjna'
Union ALl
Select 'shakuntala-anjna-sharat', 'Shakuntala'
Union ALl
Select 'shakuntala-anjna-sharat', 'Sharat'
GO

Select * From abc返回

Strng
-------
shakuntala
shakuntala-anjna
shakuntala-anjna-sharat

我想使用表abc更新表def,以便更新后Select * From abc返回

Strng
-------
Shakuntala
Shakuntala-Anjna
Shakuntala-Anjna-Sharat

2 个答案:

答案 0 :(得分:0)

如果def表中的列包含ID,我将使用WHILE

这样,您可以使用CURSOR

DECLARE @s VARCHAR(256), @i VARCHAR(256);

DECLARE c CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY 
FOR SELECT Strng, Initcap FROM def;

OPEN c;
FETCH c INTO @s, @i;

WHILE @@FETCH_STATUS = 0 BEGIN
    UPDATE abc 
    SET Strng = REPLACE(Strng,@i, @i)
    WHERE Strng = @s;

    FETCH c INTO @s, @i;
END

CLOSE c;
DEALLOCATE c;

Select * From abc

答案 1 :(得分:0)

*************警告********************  切勿在生产中使用此代码  这应被视为仅仅是演示  如何实现递归更新。  音量大时,效果会不佳

对于尝试将单词大写的尝试  相当差,因为大写有太多的规则取决于  关于地区,语言规则和习俗。

在SQL Server中,没有使用CLR函数的简便方法 *************警告********************

If Object_Id('tempdb..#abc','U') is not null
    Drop table  #abc
Go
Create Table #abc
(
    Strng varchar(max)

)
GO
Insert #abc
Select 'shakuntala'
Union All
Select 'shakuntala-anjna'
Union All
Select 'shakuntala-anjna-sharat'
GO

If Object_Id('tempdb..#def','U') is not null
    Drop table  #def
Go
Create Table #def
(
    Strng varchar(max),
    Initcap varchar(max)
)
GO
Insert #def
Select 'shakuntala', 'Shakuntala'
Union All
Select 'shakuntala-anjna','Anjna'
Union ALl
Select 'shakuntala-anjna','Shakuntala'
Union All
Select 'shakuntala-anjna-sharat', 'Anjna'
Union ALl
Select 'shakuntala-anjna-sharat', 'Shakuntala'
Union ALl
Select 'shakuntala-anjna-sharat', 'Sharat'
go

select *
from #abc a

while @@RowCount > 0
begin
    update a
    set a.Strng = replace(a.Strng, d.Initcap, d.Initcap)
    from #abc a
    inner join #def d
    on d.Strng = a.Strng
    and a.Strng not like '%' + d.Initcap + '%' collate Latin1_General_100_CS_AS
end

select *
from #abc a

上面的代码给出了所需的输出