2

I have 2 tables:

tblFoo:

Id | MessageId | SenderName

tblBar:

MessageId | Name

I need to update all the rows in tblFoo with the MessageId from tblBar where SenderName starts with Name. e.g.

tblFoo:

Id     | MessageId | SenderName
-------+-----------+--------------------
365175 | NULL      | x.y.z.abc.def.ghi
535646 | NULL      | a.b.c.fjdkf.dsfjdsf:a
535647 | NULL      | a.b.c.sdjskfj.dsfjds:b

tblBar:

MessageId                             | Name
--------------------------------------+--------
9B30FCD1-F063-4B7F-887B-65288C3681D3  | x.y.z
56FBEF0F-8C29-4614-8894-4F64A515659A  | a.b.c

So in tblFoo Id=365175 would end up with MessageId = 9B30FCD1-F063-4B7F-887B-65288C3681D3 and Id=535646 would end up with MessageId = 56FBEF0F-8C29-4614-8894-4F64A515659A and Id=535647 would also end up with MessageId= 56FBEF0F-8C29-4614-8894-4F64A515659A

So far I have

begin transaction
    update tblFoo
    set MessageId = 
    (
        select MessageId
        from tblBar
        where [Name] ???
    );
    rollback transaction

I can't do

where [Name] like

as [Name] is a substring of SenderName.

Or do I need to use a temp table?

3
  • Tag your question with the database you are using. Commented Jun 7, 2017 at 11:50
  • Is it possible, that there are more than one entries in tblBar, where the Name matches the SenderName? However, you are looking for something like LIKE SenderName=tblBar.Name + '%'... Commented Jun 7, 2017 at 11:52
  • No, there shouldn't be more than one match. Commented Jun 7, 2017 at 11:55

2 Answers 2

1

You can use the inner join as below.

update foo set messageid = br.messageid
from
tblFoo foo
inner join 
tblBar br 
on foo.senderName like ltrim(br.Name) + '%'
Sign up to request clarification or add additional context in comments.

Comments

0

Your code looks like SQL Server. You can do this using something like:

update h
    set MessageDefinitionId = (select MessageDefinitionId
                               from Sentilan2.msg.tblMessageDefinition md
                               where h.SenderName like md.[Name] + '%'
                              );
    from h;

Your code is rather hard to follow because you define tables tblFoo and tblBar, but the sample code uses different table names.

Also note that this assumes that there is only one match. You might want top 1 in the subquery to avoid run-time errors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.