原始和更新在同一个字段sql server中

时间:2012-10-05 22:21:49

标签: sql sql-server-2008

我有这个问题给你,为什么这会给我更新的价值与原来在同一领域“俄亥俄州”的原始...现在在proc“俄亥俄州OH”我只想要更新的价值。函数在proc中使用它之前只返回我测试过的一个值。提前感谢你们对它们进行调查。

CREATE PROC [dbo].[Changestringstate] 
AS 
    UPDATE stage.statetable 
    SET    originalstatename = Rtrim(originalstatename) --avoiding trailing space issues 

    UPDATE stage.statetable 
    SET    originalstatename = Replace(originalstatename, 
                               Substring (originalstatename, 
                               Len (originalstatename) - ( 
                               Charindex(' ', Reverse( 
                               originalstatename)) ) + 1, Len(originalstatename) 
                               ), 
           dbo.Changefunction(originalstatename)) 

1 个答案:

答案 0 :(得分:0)

考虑这个例子

create table statetable
(
  originalstatename varchar(100)
);
insert statetable values ('ohio oh');
GO

CREATE PROC [dbo].[Changestringstate] 
AS 
    UPDATE statetable 
    SET    originalstatename = Rtrim(originalstatename) --avoiding trailing space issues 

    UPDATE statetable 
    SET    originalstatename = Replace(originalstatename, 
                               Substring (originalstatename, 
                               Len (originalstatename) - ( 
                               Charindex(' ', Reverse( 
                               originalstatename)) ) + 1, Len(originalstatename) 
                               ), 
           'ohia') 
GO
exec changestringstate;
select * from statetable;

--- result
ohioohia

你的过程在做什么:

整个SUBSTRING块执行一项操作,即删除最后一个空格后的所有内容。这是排除尾随空格,因为它们在之前的UPDATE中被删除。它的作用的例子:

state name    |  Substring result
Ohio OH          " OH"
Mi Ohio OH       " OH"
New York NY      " NY"

然后是REPLACE块,它会查找substring result,并用dbo.Changefunction()中的任何内容替换每次出现的内容。让我们说它回来了“xyz”。

state name    |  Substring result | after replace
Ohio OH          " OH"            | Ohioxyz
Mi Ohio OH       " OH"            | Mixyzioxyz
New York NY      " NY"            | New Yorkxyz

希望能帮助您了解您的过程,以便您可以相应地修复它。