如果记录存在则返回ID,否则插入并返回ID

本文关键字:ID 返回 插入 如果 记录 存在 | 更新日期: 2023-09-27 18:08:54

我有下面的c#代码来检查记录是否不存在,插入并返回id。但我还需要,如果记录存在,它会返回值。为了实现这一点,我应该对c#和SQL部分进行哪些更改?数据库为sQL server。我还需要使用ExecuteScalar()吗?

con.Open();
// Insert ClinRefFileTypeMaster
string command1 = string.Format(
    "if NOT exists (select * from [ClinRefFileTypeMaster] where [ClinRefTypeName] = '{0}') Insert into [ClinRefFileTypeMaster] ([ClinRefTypeName]) output INSERTED.[ClinRefTypeID] VALUES('{0}')",
      dataToParse[i][0]
      );
SqlCommand ClinRefFileTypeMaster = new SqlCommand(command1, con);
// check if there is an value 
object checkValue = ClinRefFileTypeMaster.ExecuteScalar(); 
if (checkValue != null)
    ClinRefFileTypeId = (int)checkValue;

如果记录存在则返回ID,否则插入并返回ID

为您完成所有工作的存储过程看起来像.....

CREATE PROCEDURE usp_Get_ClinRefTypeID
  @ClinRefTypeName  VARCHAR(100),
  @ClinRefTypeID    INT OUTPUT
AS
BEGIN
  SET NOCOUNT ON;
    DECLARE @NewID TABLE(ClinRefTypeID INT);
  SELECT @ClinRefTypeID = [ClinRefTypeID]
  FROM [ClinRefFileTypeMaster] 
  where [ClinRefTypeName] = @ClinRefTypeName;
  IF (@ClinRefTypeID IS NULL)
    BEGIN
        INSERT INTO [ClinRefFileTypeMaster] ([ClinRefTypeName]) 
        OUTPUT inserted.[ClinRefTypeID]  INTO @NewID(ClinRefTypeID)
        VALUES(@ClinRefTypeName)
        SELECT @ClinRefTypeID = [ClinRefTypeID] FROM @NewID
    END
END

你的c#代码看起来像.....

con.Open();
// Insert ClinRefFileTypeMaster
    SqlCommand cmd = new SqlCommand("usp_Get_ClinRefTypeID", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@ClinRefTypeID", SqlDbType.Int).Direction = ParameterDirection.Output;
    cmd.Parameters.Add(new SqlParameter("@ClinRefTypeName", dataToParse));
// get the value back from the output parameter 
    cmd.ExecuteNonQuery();
    int ClinRefTypeName = Convert.ToInt32(cmd.Parameters["@ClinRefTypeID"].Value);

有很多方法可以做到这一点。1)你可以在内联Sql中完成这一切;2)你可以在存储过程中完成这一切;3)你可以在代码中完成这一切,但拆分代码,因为这段代码做得太多了。一般情况下,我会避免使用相同的方法插入/查询。

也尝试使用SqlParameters而不是将查询构建为字符串concat。

我建议这样做,使代码更具可读性

    public int InsertAndRetrieveClientRefId(string clientRefTypeName)
    {
        int id = GetIdIfRecordExists(clientRefTypeName);
        if (id == 0)
        { 
            // insert logic here
            id = GetIdIfRecordExists(clientRefTypeName);
        }
        return id;
    }
    public int GetIdIfRecordExists(string clientRefTypeName)
    {
        int id = 0;
        string command = "select id from ClinRefFileTypeMaster where ClinRefTypeName = @ClinRefTypeName";
        SqlParameter nameParameter = new SqlParameter("@ClinRefTypeName", System.Data.SqlDbType.NVarChar, 10) { Value = clientRefTypeName };
        using (SqlConnection connection = new SqlConnection("ConnectionString"))
        {
            using (SqlCommand cmd = new SqlCommand(command))
            {
                cmd.Parameters.Add(newParameter);
                connection.Open();
                cmd.Connection = connection;
                int.TryParse(cmd.ExecuteScalar().ToString(), out id);
            }
        }
        return id;
    }

在数据库中执行所有这些操作,即存储过程

if not exists (select 1 from  [ClinRefFileTypeMaster] where [ClinRefTypeName] =@name)
begin
Insert into [ClinRefFileTypeMaster] ([ClinRefTypeName]) values (@name) 
end
else
begin
select (as desired) from ClinRefFileTypeMaster where where [ClinRefTypeName] =@name
end

this将插入新记录或者选择已经插入的信息

您还需要在SQL语句中添加IF EXISTS子句,检查相同的条件,并提供返回值的逻辑。

如果你需要使用ExecuteReader从数据库返回值,那么使用它似乎会更好。

¢

2我个人会将逻辑分成两个查询,并在c#中运行If语句检查值是否在数据库中,然后更新数据库,否则从数据库返回一个值

conn.open()
int CheckDb;
String Command1 = "select * from [ClinRefFileTypeMaster] where [ClinRefTypeName] = @ClinRefFileTypeId";
using (SqlCommand ClinRefFileTypeMaster = new SqlCommand(command1, con);
    {
         cmd.Parameters.AddWithValue("@ClinRefFileTypeId", {0});
         CheckDb = (int)ClinRefFileTypeMaster.ExecuteScalar();
     }
If (CheckDb != 0)
    //Logic for returning the value from the database
Else
    //Here you can request user check data or insert the value into the database.

如果要执行insert操作,我认为最好调用存储过程并在过程中编写查询。这样会更安全。

SqlCommand command = new SqlCommand("procedureName",con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue(“@value1”, txtValue1.Text);
command.Parameters.AddWithValue(“@value2”, Value2);
int value = command.ExecuteScalar();

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='') 
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END

如果你想传递查询字符串,你可以调用select query,如果它返回null,执行插入操作,并使用scope_Identity()来获得ID

INSERT INTO YourTable(val1, val2, val3 ...) 
VALUES(@val1, @val2, @val3...);
SELECT SCOPE_IDENTITY();