I am a programmer, can someone help me?

Majeed Purseyedmahdi 41 Reputation points
2021-07-06T11:13:04.833+00:00

112119-capture1.jpg

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,918 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,723 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,421 Reputation points
    2021-07-06T13:16:54.043+00:00

    Using SQL-Server the following first checks if there are rows (there are actually simpler ways to do this but this here has less of an impact on the server), if not return 1 else return the last id.

    Note on the table name, this should really be a parameter to the SqlCommand object which is easy enough to do.

    public class SqlOperations
    {
        /// <summary>
        /// SQL-Server name
        /// </summary>
        public static string Server { get; set; }
        /// <summary>
        /// Database in Server
        /// </summary>
        public static string Database { get; set; }
    
        public static int GetLastIdentifier()
        {
            using var cn = new SqlConnection($"Server={Server};Database={Database};Integrated Security=true");
    
            var selectStatement =
                "SELECT SUM(row_count) AS rows FROM sys.dm_db_partition_stats " +
                "WHERE object_id = OBJECT_ID('Customers') AND index_id < 2 " + 
                "GROUP BY OBJECT_NAME(object_id);";
    
            using var cmd = new SqlCommand(selectStatement, cn);
    
            cn.Open();
    
            var identifier = Convert.ToInt64(cmd.ExecuteScalar());
            if (identifier == 0)
            {
                return 1;
            }
            else
            {
                cmd.CommandText = "SELECT IDENT_CURRENT('Customers')";
                return (int) Convert.ToInt64(cmd.ExecuteScalar());
            }
    
        }
    
    }
    

    Example

    SqlOperations.Server = ".\\SQLEXPRESS";
    SqlOperations.Database = "NorthWind2020";
    var id = SqlOperations.GetLastIdentifier().ToString();
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.