[英]How to check if a row is present in SQL Server table or not?
I am trying to check if there is a row present in a SQL Server table or not. 我正在尝试检查SQL Server表中是否存在行。
If the row exists (on a particular TicketID
), it should show a messagebox that you can't continue further as there is already an entry in database. 如果该行存在(在特定的TicketID
),它应该显示一个消息框,由于数据库中已有条目,因此无法继续进行。 But if there isn't, it should insert some records (on that particular TicketID
). 但如果没有,它应该插入一些记录(在特定的TicketID
)。
I tried try and catch but wasn't able to do it : 我试过尝试捕获但是无法做到:
Here is the code of query: (hardcoded ticketID
for example) 这是查询代码ticketID
例如硬编码的ticketID
)
bool no;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString());
con.Open();
cmd.CommandText = "SELECT EngineerVisited from tblTicketTechnical where TicketID=1";
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
bool = rdr.GetBoolean(0);
}
con.Close();
}
catch
{
MessageBox.Show("Cannot continue");
}
I would really appreciate if someone could suggest a function that will return true if row is found and return false, if it isn't. 如果有人可以建议一个函数,如果找到行,该函数将返回true,否则返回false,我将不胜感激。
You should follow the same logic in code as the logic you state in English: if there's already a ticket show a message and if not, insert some data. 您应该在代码中遵循与您用英语说明的逻辑相同的逻辑:如果已经有票证显示消息,如果没有,则插入一些数据。
var checkQuery = "SELECT COUNT(*) FROM tblTicketTechnical where TicketID=1";
var command = new OleDbCommand(checkQuery, con);
con.Open();
int count = (int)command.ExecuteScalar();
if(count > 0)
{
//Already exists, show message
}
else
{
var insertQuery = "INSERT INTO tblTicketTechnical(col1, col2) VALUES('val1', val2')";
con = new OleDbCommand(insertQuery, con);
con.ExecuteNonQuery();
}
Please mind that this is written out of my head and not tested. 请注意,这是写在我脑海中而未经过测试。 Nor have I implemented exception handling. 我也没有实现异常处理。 This is just to show the logic how you can perform what you want to achieve. 这只是为了展示如何执行您想要实现的目标的逻辑。
您可以使用HasRows财产SQLDataReader
。
A catch
block will only be executed if your code throws an exception
. 只有在代码抛出exception
才会执行catch
块。 Here it is simply not happening. 这里根本没有发生。
Instead of Try/Catch use if
statements and checks on your query results. 代替Try / Catch使用if
语句并检查您的查询结果。
Create procedure and code like this 像这样创建过程和代码
IF NOT EXISTS (SELECT 1 FROM youtable WHERE id= @id)
BEGIN
RAISERROR ('Record Exists', 16, 2)
END
ELSE
Begin
INSERT INTO YOURTABEL(COLUM1,COLUM2) VALUES(VALUE1, VALUE2)
END
and then by try catch you can show message to user 然后通过try catch您可以向用户显示消息
您可以使用DataTableReader.HasRows属性
The HasRows property returns information about the current result set
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.