0

I have the below C# code to check if the record does not exist, insert and return id. But also I need if the record exists, it return the value. What change should I make to C# and SQL part for this to happen? Database is sQL server. Do I still have to use ExecuteScalar() for this?

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;
5
  • 3
    Probably you need the MERGE statement
    – Steve
    Aug 19, 2015 at 12:33
  • Maybe split the statements. Only insert in the if-block. select outside. SQL is pretty good with caching, if you've just inserted something selecting it is probably going to be very fast. Also the query is hard to read, please make into a multi-line string by starting it with @.
    – MrFox
    Aug 19, 2015 at 12:36
  • 1
    This look Little Bobby Tables unaware.
    – Uwe Keim
    Aug 19, 2015 at 12:37
  • 1
    Similar solution is here
    – PM.
    Aug 19, 2015 at 12:37
  • Or use a DECLARE recordId int; and then SELECT recordId = idColumn FROM tbl... Aug 19, 2015 at 12:38

5 Answers 5

2

A stored procedure to do all the stuff for you would look something like.....

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

And your C# code would look something like.....

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
  • 1
    Yeah, I strongly recomand this way! Much safer and way easier to mantain.
    – CiucaS
    Aug 19, 2015 at 12:55
1

There are many ways to achieve this. 1) You can do it all in inline Sql 2) you can do it all in stored proc. 3) You can do it all in code but split the code as this code is frankly doing too much. In general I would avoid insert/query in the same method.

Also try to use SqlParameters instead of building the query as string concat.

I would propose something like this which makes the code a bit more readable

    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;
    }
2
  • Thanks, this worked for me as using store procedure was not an option for me. I think you only forgot to add the nameParameter to the command ! I did that and it worked great. Aug 19, 2015 at 17:04
  • glad it worked. I've updated the answer to add the parameter to the command.
    – Qudoos
    Aug 19, 2015 at 19:02
1

do all this in database i.e in store procedure

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 will either insert new record or it will select already inserted information

1

Youll need to add an IF EXISTS clause to the SQL statement as well, checking for the same conditions, and providing logic to return a value.

It seems using ExecuteReader would be better if you need it to return the value from the database.

2¢ I personally would split the logic into two queries and run the If statement within c# checking if the value is in the database, then updating the database else returning a value from the database

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.
1

if you want to perform Instert operation, I think its better you call a stored procedure and write your query in the procedure. It will be safer.

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

If you want to pass the querystring, you can call select query and if it returns null perform a insert opeartion and use scope_Identity() to get the ID

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.