简体   繁体   English

Select 并计算有多少行

[英]Select and count how many rows

Sorry, I'm just learning C#. I'm use to HTML/PHP then actual programming.抱歉,我刚刚学习 C#。我习惯于 HTML/PHP 然后实际编程。

I'm looking to use SQL SELECT to view data from search result however it's likely that because of multiple LIKE it may bring multiple rows (which I want) however if it brings multiple rows instead of selecting the first row to display I want a IF message stating that there is more than one row matching the criteria.我正在寻找使用 SQL SELECT 从搜索结果中查看数据但是很可能因为多个 LIKE 它可能会带来多行(我想要)但是如果它带来多行而不是选择第一行来显示我想要一个 IF消息指出有不止一行符合条件。 Below is my current code (I have removed some code from it after if (recordfound) to shorten the code for this question)下面是我当前的代码(我在if (recordfound)之后删除了一些代码以缩短这个问题的代码)

SqlConnection con1 = new SqlConnection(@Settings.Default.database);
con1.Open();
string qu = "SELECT * FROM addresses WHERE road LIKE '%" + inclocroad.Text.Trim() + "%' OR postcode LIKE '%" + inclocroad.Text.Trim() + "%' OR full_address LIKE '%" + inclocroad.Text.Trim() + "%' OR Property LIKE '%" + inclocno.Text.Trim() + "%' OR full_address2 LIKE '%" + inclocroad.Text.Trim() + "%' ";
SqlCommand cmd1 = new SqlCommand(qu, con1);
SqlDataReader dr = cmd1.ExecuteReader();
bool recordfound = dr.Read();
if (recordfound)
{
    //Displays data from row
} 
else
{
    messagebox.show("No data found");
}

Example例子

User clicks button用户点击按钮

SQL uses SELECT QUERY where the user has written the search result SQL 使用 SELECT QUERY 用户在其中写入了搜索结果

IF SELECT QUERY has more than 1 row then display message box IF SELECT QUERY 多于 1 行然后显示消息框

Otherwise show the only row matching the search result.否则显示唯一匹配搜索结果的行。

You can use this if you are hoping to load data using DataTable.如果您希望使用 DataTable 加载数据,则可以使用它。

    SqlCommand cmd1 = new SqlCommand(qu, con1);
    SqlDataReader dr = cmd1.ExecuteReader();
    bool recordfound = dr.Read();

    DataTable dt = new DataTable();
    if (recordfound)
    {
         dt.Load(reader);
    } 
    
    int numRows= dt.Rows.Count;
    if(numRows > 1){
        messagebox.show("Data found"+ numRows);
    }
    else
    {
        messagebox.show("No data found");
    }

Well, why don't you just count them:好吧,你为什么不数一下它们:

SELECT COUNT(1)... . SELECT COUNT(1)... .

Since we are talking about just few rows it doesn't hurt performance or anything.由于我们只讨论几行,因此不会影响性能或任何其他内容。

It's so simple... I just was having a moment.很简单...我只是有片刻。

I've made two SQL's with a IF query if it held more results or not.如果它是否包含更多结果,我已经用 IF 查询创建了两个 SQL。 The first SQL being a COUNT using ExecuteScalar than using a IF statement if it did hold more than one record.第一个 SQL 是使用 ExecuteScalar 的 COUNT 而不是使用 IF 语句,如果它确实包含多个记录。

Thanks for the help.谢谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM