从C#WPF中的select查询中获取最后一个ID

本文关键字:获取 最后一个 ID 查询 C#WPF 中的 select | 更新日期: 2023-09-27 18:26:44

我想得到最后一个被选中的人ID。

string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
SqlCommand cmd = new SqlCommand(personID, con);
SqlDataReader reader = cmd.ExecuteReader();

var lastSelectedSingleClientPhoneId = reader.GetDecimal(0);

但不幸的是,它没有起作用。我已经尝试过获取int16、int32和int64。当我使用INSERT时,我可以使用以下选项获取ID:

SELECT SCOPE_IDENTITY();

在下面插入命令:

string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (@firstName,@secondName);SELECT SCOPE_IDENTITY();"; 
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("@firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("@secondName", txt_secondName.Text);
SqlDataReader reader = cmd.ExecuteReader(); 
reader.Read(); 
var lastInsertedPersontId = reader.GetDecimal(0);'

从C#WPF中的select查询中获取最后一个ID

这应该返回Persons数据库表中以"XYZ"开头的所有Person。

string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
using(var cmd = new SqlCommand(personID, con))
using (var reader = cmd.ExecuteReader())
{
    while(reader.Read())
    {
        Console.WriteLine(reader.GetValue(0));
    }
}

我很感激您正在寻找一个调用GetXXX的类型,但您可以很容易地扩展此伪代码来确定合适的类型。

您可以尝试将两个SQL语句组合为一个CommandText值,然后使用ExecuteScalar返回最后插入的ID

string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (@firstName,@secondName); SELECT SCOPE_IDENTITY();"; 
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("@firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("@secondName", txt_secondName.Text);
int personID = (int)cmd.ExecuteScalar();
/// ... convert integer value to a string or do something

您也可以尝试使用此SQL语句作为替代:

SELECT TOP 1 PersonID FROM Persons ORDER BY PersonID DESC;