开发者

Update column if another column contains a string

开发者 https://www.devze.com 2023-04-10 02:45 出处:网络
I have a table that contains three columns. column1column2column3 mytestdatatest myotherdatatest I want to insert \'somestring\' into column3 if column1 contains the value in column2

I have a table that contains three columns.

column1        column2     column3 
mytestdata     test 
myotherdata    test 

I want to insert 'somestring' into column3 if column1 contains the value in column2

The result would look like:

column1        col开发者_JS百科umn2     column3 
mytestdata     test        'somestring' 
myotherdata    test 


SQL Server:

UPDATE myTable
   SET column3 = 'somestring'
 WHERE column1 LIKE '%' + column2 + '%'


SQL Server:

UPDATE theTable SET column3 = 'somestring' 
WHERE CHARINDEX (column2, column1) > 0


You have several options, depending on the RDBMS.

For both MySQL and Oracle:

UPDATE yourTable
set column3 = 'somestring'
where INSTR(column2, column1) > 0

For SQL Server:

UPDATE yourTable
set column3 = 'somestring'
where CHARINDEX(column1, column2) > 0


You could do something like below

UPDATE tmp
SET
   column3 = (CASE WHEN tmp.column1 like '%' + tmp.column2 + '%' THEN 'something' ELSE tmp.column3')
FROM
    tablename tmp
0

精彩评论

暂无评论...
验证码 换一张
取 消