【问题标题】:How to compare two table columns in sql server using c#如何使用c#比较sql server中的两个表列
【发布时间】:2014-07-03 11:30:58
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你卡在哪里了?您可以使用相等运算符 (==) 比较值,您可以基于该比较与条件块 if (someCondition) { ... } 有条件地运行代码,您可以通过多种不同的方式连接到数据库。您尝试了哪些方法,哪些方法无效?

标签: c# sql


【解决方案1】:

这里没有太多信息。

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

所以在 SQL 中做这样的事情

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

把它做成一个存储过程,然后用c#调用run这个过程。

这只是一个示例,并且基于您实际上希望在 SQL 中完成并使用 c# 运行它的假设

【讨论】:

    【解决方案2】:

    尝试以下操作:

    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
    

    结果:

    假设您的两个表名称为 'Table1' & 'Table2'

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

    注意:这是与Temporay Table 一起使用的示例,请不要按“原样”使用。根据您的需要进行更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-20
      • 2012-08-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多