【问题标题】:SQL C++/CLi - Way to know if something is in a table if yes use it's id, if not generate the new id and grab itSQL C++/CLi - 知道某物是否在表中的方法,如果是,则使用它的 id,如果不是,则生成新的 id 并获取它
【发布时间】:2020-11-30 11:45:41
【问题描述】:

我有一个包含这些链接的数据库: MCD

我想在“人员”表中添加新值。 我做了这个查询:

INSERT INTO Adresse (NoRue, Addresse, Ville, CP)
VALUES ('420','Rue des Lacs','Paris','75016');
DECLARE @Id1 AS int = @@identity;
INSERT INTO Date (Date)
VALUES (1999-02-21);
DECLARE @Id2 AS int = @@identity;
INSERT INTO Personnel (NomPersonnel, PrenomPersonnel, IdAdresse, IdDate)
VALUES ('Michel','Jean',@Id1, @Id2);

但每次我创建新值时,它都会创建一个新日期。我想知道我是否可以检查日期是否已经存在,如果可以插入 FK Personnel.IdDate。如果注意创建一个新的日期并在 Personnel.IdDate 中插入 FK。

感谢您的宝贵时间。

【问题讨论】:

  • 仅供参考 "INSERT INTO Date (Date) VALUES (1999-02-21);" 不会像你想的那样做。如果您使用较新的日期和时间数据类型,它要么会出错,要么会插入 datetime 1905-05-31T00:00:00.000: 1999-02-21 = 1976 = DATEADD(DAY,1976,'19000101') = 1905-05-31T00:00:00.000

标签: c++ sql .net sql-server


【解决方案1】:

我做到了:

int id_date = dataAccess->actionRowsID("SELECT * FROM Date WHERE Date IN ('" + getDate() + "')");
    if (id_date == 0 )
    {
        return "INSERT INTO Adresse (NoRue, Addresse, Ville, CP)" +
                    "VALUES('420', 'Rue des iddate0', 'City', '75016');" +
                    "DECLARE @Id1 AS int = @@identity;" +
                    "INSERT INTO Date(Date)" +
                    "VALUES('" + getDate() + "');" +
                    "DECLARE @Id2 AS int = @@identity;" +
                    "INSERT INTO Personnel(NomPersonnel, PrenomPersonnel, IdAdresse, IdDate)" +
                    "VALUES('" + getNom() + "', '" + getPrenom() + "', @Id1, @Id2);";
    }
    else
    {
        return "INSERT INTO Adresse (NoRue, Addresse, Ville, CP)" +
                    "VALUES('420', 'Rue des Iddatepas0', 'Stylax', '75016');" +
                    "DECLARE @Id1 AS int = @@identity;" +
                    "INSERT INTO Personnel(NomPersonnel, PrenomPersonnel, IdAdresse, IdDate)" +
                    "VALUES('" + getNom() + "', '" + getPrenom() + "', @Id1, "+ id_date + ");";
    }   
}

actionRowsId 在哪里

int NS_Composants::CL_CAD::actionRowsID(String^ rqsql)
{
    int id;
    setSQL(rqsql);
    comm->CommandText = this->rq_sql;   //comm is SqlCommand object 
    conn->Open();                       //conn is the SqlConnection object
    id = Convert::ToInt32(comm->ExecuteScalar());
    conn->Close();
    return id;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多