如何比较TSQL中第一列中的每个字符串与第二列中的每个字符串?

时间:2018-08-08 08:23:17

标签: sql sql-server-2008 tsql

这是我尝试的代码:

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  

我在查询中得到两列,均为nvarchar(255)。 我想将第一列中的每个值与第二列中的每个值进行比较。可以通过循环内的循环来实现,但是我不知道该如何处理光标部分。

我应该放置一个变量并分别保持获取状态吗? 还是有其他办法可以解决问题?

1 个答案:

答案 0 :(得分:2)

我认为您不需要光标,可以使用select:

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