Vlad
Vlad

Reputation: 2773

How to compare each string from first column with each string in second column in TSQL?

Here is the code I tried:

declare @o1 nvarchar(255)
declare @o2 nvarchar(255)

declare data cursor for
select o1.Name, o2.Name from MyDB.dbo.Table1 as o1, MyDB.dbo.MyTable2 as o2;

OPEN data;  

-- Perform the first fetch.  
FETCH NEXT FROM data into @o1, @o2;  

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.  
WHILE @@FETCH_STATUS = 0  
BEGIN  
   -- This is executed as long as the previous fetch succeeds.  

   FETCH NEXT FROM data INTO @o1, @o2;  
   Print 'Name1: ' + @o1

   WHILE @@FETCH_STATUS = 0  
    BEGIN  
       -- This is executed as long as the previous fetch succeeds.  

       FETCH NEXT FROM data INTO @o1, @o2;  
       Print 'Name2: ' + @o2
    END 
END  
CLOSE data;  
DEALLOCATE data;  
GO  

I am getting two columns in my query and both are nvarchar(255). I want to compare each value from the first column with each value of the second column. That can be achieved with loop inside a loop, but I don't know what should I do with the cursor part.

Should I put a variable and keep fetch status separately? Or somethings else will do the trick?

Upvotes: 0

Views: 72

Answers (1)

Mohammed HIMMI
Mohammed HIMMI

Reputation: 39

I think that you don't need a cursor you can use select :

Select o1, O2
from table1
where o1 in (select o2 from table1)

Upvotes: 2

Related Questions