如何使用c#比较sql server中的两个表列

时间:2014-07-03 11:30:58

标签: c# sql

我想比较两个不同的表列(ID),如果两个id相同,我想插入位置名称在第一个表中有第二个表

Table 1
-------
    Id   Name
    ---------
    1    Hyd
    2    Banglore
    ---------

Table 2
-------
    Id Name
    -------
    1 
    2 

从第一个表id和第二个表id如果两者相等,我想在第二列中插入名称列,该列存在于同一个id行中使用C#帮助我

2 个答案:

答案 0 :(得分:1)

这里没有很多信息。

这假设当你说c#时,你实际上是指C#到SQL。

所以在SQL中做这样的事情

UPDATE Table2
SET Table2.Name = Table1.name
FROM Table1
WHERE Table2.ID = table1.ID

将其设为存储过程,然后使用c#调用运行该过程。

这只是一个例子,它是基于你实际上想要在SQL中完成并使用c#来运行它的假设

答案 1 :(得分:0)

请尝试以下操作:

create table #testsource
(ID int,city nvarchar(200))

insert into #testsource (ID,city)
values(1,'mumbai'),
(2,'Pune')

select *from #testsource

create table #testdestination
(ID int,city nvarchar(200))

//insert rows in table
insert into #testdestination (ID,city) values(1,''),(2,''),(3,'')

//select rows from table
select *from #testdestination

//get the values from Source table and update to Destination table
update #testdestination set city=s.city 
from #testsource s 
where s.ID=#testdestination.ID

select *from #testdestination

drop table #testsource
drop table #testdestination

<强>结果: enter image description here

假设您的两个表名称包含&#39;表1&#39; &amp; &#39;的表2 &#39;

CREATE PROCEDURE [dbo].[p_UpdateDestinationTable]
AS
BEGIN
UPDATE Table2
SET Table2.Name = t1.name
FROM Table1 t1
WHERE Table2.ID = t1.ID

注意:这是与Temporay使用的示例Table plelase 不要使用&#34;&#34; 。根据您的需求进行更改。