开发者

T-SQL query to remove non matching value from ColumnA where value doesn't exist in ColumnB

I have two databases, with the following tables:

DatabaseA TableA ColumnA (varChar(10)

DatabaseB TableB Co开发者_如何学GolumnB (varChar(10)

I need a query that:

  • Ignores NULLs or empty strings
  • Finds rows where the value of ColumnA does not exist in columnB

    • In this case, replaces the value of the non matching row in ColumnA with '' (empty string)

This is in a MS SQL Server 2008 environment.


You can do this with a LEFT OUTER JOIN as shown below:

UPDATE TableA
SET columnA = ''
FROM
    TableA 
    LEFT JOIN TableB ON TableA.columnA = TableB.columnB
WHERE
    TableA.columnA IS NOT NULL AND TableA.columnA <> '' AND
    TableB.columnB IS NULL;


UPDATE TableA 
SET ColumnA = ''
WHERE  ColumnA IS NOT NULL 
  AND ColumnA <> '' 
  AND NOT EXISTS
     (
     SELECT *
     FROM TableB WHERE TableB.ColumnB = TableA.ColumnA
     )
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜