English 中文(简体)
页: 1
原标题:Replace in TSql

I want to update a row which is in format like this ABC - DEF - GHI - ABD,
Using a cmd like this UPDATE tbl SET col = Replace(col,@var, ) WHERE Pk=something. How can I remove the trailing or leading hyphens? For exmaple if @var is GHI, after replace, row value should be ABC-DEF-ABD or if @var is ABC then value should be DEF - GHI - ABD.

最佳回答

首先,完全同意上述意见。 改变数据ema,在数据库一栏中不储存有限价值清单。

但是,如果无法做到这一点,请说明:

Update Table Set 
   colName = Replace(Replace(colName,  -   + @var,   ), @var +   - ,   )
Where pk = @pk
问题回答

添加外加——在座尾,用所附的干ash取代@var,然后拆除拖车——如果你重新做的话。

UPDATE tbl
    SET col = LEFT(REPLACE(col +   -  , @var+  -  ,   ), LEN(col)-6)
    WHERE Pk = something

如何:

UPDATE tbl SET col = replace(replace(col, @var +   –  ,   ),   –   + @var,   )

内部取代所有中间和“牵头”的事例,外部取而代之的是任何“最终”的事例。

如果有单例,例如GHI,则添加一个外在字:

UPDATE tbl SET col = replace(replace(replace(col, @var +   –  ,   ),   –   + @var,   ), @var,   )

您可以使用:

-- 1: replace(col,@var,   ) => your replacement
-- 2: replace(#1,   -  ,  - ) => remove spaces
-- 3: replace(#2,  -  ,   ) => remove first hyphen and space
-- 4: replace(#3,   - ,   ) => remove last hyphen and space

UPDATE tbl
   SET col = replace(replace(replace(replace(col,@var,   ),   -  ,  - ),  -  ,   ),   - ,   )        
 WHERE Pk=something




相关问题
How to write this T-SQL WHERE condition?

I ve got two tables: TableA Col1 Col2 TableB Col3 Col4 I want to join them together: SELECT * from TableA join TableB ON (...) Now, in place of ... I need to write an expression ...

Customer and Order Sql Statement

TSQL query to select all records from Customer that has an Order and also select all records from customer that does not have an Order. The table Customer contains a primary key of CustomerID. The ...

Recommended way of querying multiple Versioned tables

Have a win 2003 box with MSSQL 2005 running on it. There is a database which is populated every morning with new/modified SalesOrder made the previous day. The database has several tables: SalesOrder, ...

update duplicate record

I have a table with the following fields Id Name IsPublic i need to write a sql query that updates IsPublic to false where name has a duplicate. Only one of the duplicates should have IsPublic = ...

Define variable to use with IN operator (T-SQL)

I have a Transact-SQL query that uses the IN operator. Something like this: select * from myTable where myColumn in (1,2,3,4) Is there a way to define a variable to hold the entire list "(1,2,3,4)"? ...

Selecting records during recursive stored procedure

I ve got a content management system that contains a hierarchical structure of categories, with sub-categories subject to different ordering options at each level. Currently, that s retrieved by a (...

热门标签