-8

我有一个 SQL Server 2012 数据库,我希望使用 select 语句对其进行查询,并将出现的每个结果放在任何类型的集合类型中,例如:List

问题是我从来没有做过SQL Queering,我真的需要你的帮助,

我需要在名为“yt2016”的表中的标记列中搜索值...您可以通过编写代码来帮助我,我将非常感激,在此先感谢。

4

1 回答 1

2
public class Foo
{
    // some properties
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    // ...
}

public static IEnumerable<Foo> GetAllFoos(String columnFilter = null)
{

    const string sql = @"SELECT 
                    Columns ...
                 FROM 
                    dbo.TableFoo
                 WHERE
                    @SomeColumn IS NULL OR SomeColumn = @SomeColumn
                 ORDER BY
                     OrderColumn1 ASC, OrderColumn2 DESC";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = new SqlCommand(sql, connection))
        {
            if (columnFilter == null)
                cmd.Parameters.AddWithValue("@SomeColumn", DBNull.Value);
            else
                cmd.Parameters.AddWithValue("@SomeColumn", columnFilter);
            connection.Open();
            using (var rdr = cmd.ExecuteReader())
            {
                var list = new List<Foo>();
                while (rdr.Read())
                {
                    var foo = new Foo();
                    foo.Prop1 = rdr.GetInt32(0);
                    foo.Prop2 = rdr.GetString(0);
                    list.Add(foo);
                }
                return list;
            }
        }
    }
}

一个更有针对性的例子可能是

using System;
using System.Data;
using System.Data.SqlClient;

public class DataAccess
{

    // This should be specific to your database.
    const string ConnectionString = 
        "Data Source=(local);Initial Catalog=Northwind;Integrated Security=true";

    const string TokenQuery @=
        "SELECT tokens FROM dbo.yt2016;"

    static IEnumerable<object> GetTokens()
    {
        using (var connection = new SqlConnection(connectionString))
        {
        // Create the Command and Parameter objects.
        var command = new SqlCommand(TokenQuery, connection);

        // Create and execute the DataReader, 
        // casting and yielding to the caller.
        connection.Open();
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return reader[0];
            }
        }
    }
}
于 2013-01-22T08:56:51.800 回答