locked
Check existence of a distinct value then insert RRS feed

  • Question

  • User821258875 posted

    hi,

    so my idea is to make a new datatable that contains a column with distinct values .i open a connection with the database to implement a stored procedure and i loop on every row to send the parameter value to the stored procedure.

    the problem is I don't know how to write it. I selected the distinct value from the table and what I want to do is compare the input parameter from the backend with the distinct value from the SQL server and if not a match I insert the row.

    another problem, the new datatable has only a single column with distinct value. how to get the whole row with all the other column values that correspond to that distinct value to insert in the database.

    the c#:

    var distinct_Round_Month = dt.DefaultView.ToTable(true, "Round_Month_ID") ;
    using (var conn = new SqlConnection(con_string))
    using (var command = new SqlCommand("UpdateMyData", conn))
    {
    command.CommandType = CommandType.StoredProcedure;
    for (int j = 0; j < distinct_Round_Month.Rows.Count; j++)
    {
    //if ((string)distinct_Round_Month.Rows[j].ItemArray[0] == "Nov-2019")
    //{
    command.Parameters.AddWithValue("@Round_Month_ID", distinct_Round_Month.Rows[j].ItemArray[0]);
    conn.Open();
    command.ExecuteNonQuery();
    conn.Close();
    //}

    }
    }

    the stored procedure:

    USE [Audit]
    GO
    /****** Object: StoredProcedure [dbo].[UpdateMyData] Script Date: 11/26/2019 10:31:30 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[UpdateMyData]

    @Round_Month_ID nvarchar(50)

    AS

    Begin

    Select Distinct
    Round_Month_ID
    FROM FindingDetails f
    IF (//the condition )
    BEGIN
    INSERT

     into //table name 

    Tuesday, November 26, 2019 10:48 AM

All replies

  • User475983607 posted

    I do not understand your code or description.  I think you are looking for TSQL code similar to the following.

    IF EXISTS(Select Round_Month_ID FROM FindingDetails)
    	BEGIN
    		--UPDATE
    	END
    ELSE
    	BEGIN
    		--INSERT
    	END

    Tuesday, November 26, 2019 12:50 PM
  • User1535942433 posted

    Hi khloud_ali39,

    Accroding to your description,I coudn't understand your requirment clearly.

    I suggest you could post an example with the data about the existing table, new table and the result table like below:

    Existing table:

    Column1 Column2 Column3

    data1       data2      data3

     New table:

     Column1 Column2 Column3

    Data1       data2      data3

     Result table:

     Column1 Column2 Column3

    Data1       data2      data3

     This will help us understand your requirement clearly and find out the solution.

     Best regards,

    Yijing Sun

    Wednesday, November 27, 2019 9:27 AM