【问题标题】:how to know record exist against relation of table in SQL Server如何知道 SQL Server 中表的关系存在记录
【发布时间】:2014-02-15 05:18:40
【问题描述】:

我在 SQL Server 数据库中有 100 个表。每个表都和Customer表有关系,每个表都有CustomerId列。

如果我尝试从表中删除客户,则会收到错误消息。

所以我想检查每个表以查看该表中是否存在CustomerId。

这在 SQL Server 中可行吗?如果记录存在于其他表中,则仅返回是/否?

【问题讨论】:

  • 您遇到什么错误?如果是,您是否在关系中选择了级联?
  • 您能给我们一个简短的表格示例吗?您到底想做什么?
  • DELETE 语句与 REFERENCE 约束“FK_FinishMaterialItem_Customer”冲突。冲突发生在数据库“PakPackages_Live”、表“dbo.FinishMaterialItem”、列“CustomerCode”中。
  • 知道我正在有条件地检查每个表。但这不是正确的方法

标签: c# asp.net sql-server database vb.net


【解决方案1】:

您可以创建一个小函数来检查 id 是否存在。

试试这个:

   bool IsIdExist(int id)
    {
        using(SqlConnection con = new SqlConnection("Connection String Here"))
        using (SqlCommand command = new SqlCommand("select count(*) from customer where id=@id", con))
        {
            command.Parameters.AddWithValue("@id", id);
            con.Open();
            int rows = Convert.ToInt32(command.ExecuteScalar());
            if (rows > 0)
                return true;

            return false;
        }            
    }

您可以如下调用上述函数:

if(IsIdExist(300))
{
//id exists
}
else
{
//id does not exist
}

【讨论】:

  • 不,先生,这不是我的要求。我想要 Sql Server 的语法,即如何知道关系表上的主键引用。如果记录存在 YES/No Only
  • @Salman:你能用例子解释一下你的要求吗?
  • 我在 Sql Server 中有 100 个表。一张桌子是客户的桌子 .ok 。现在每 100 个表都有列 CustomerID 和 Relation with Customer 主键到每个表的 forin 键和。假设一个 ID 为 1 的客户“ABC”,这 1 个 id 通过每个 100 table 。知道我是否想从 CustomerID=1 的客户运行 Qurey Delete,然后它不能被删除,因为它的关系 id 传递到其他 100 个表。我的问题是,如何知道有 1 Id 传递任何关系表只返回真或不简单:)。但我不喜欢一个一个地检查每个表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 2015-08-02
相关资源
最近更新 更多