从SQL数据库中的表中选择字段

时间:2016-03-29 15:01:46

标签: c# sql visual-studio crystal-reports

我在Visual Studio中创建了数据源,我试图通过使用存储为Reference No_的简短号码来访问名为No_的字段。

argclean="AW02464";            
string connectionString = "Data Source=ERP-SERVER; Initial Catalog=RMS2015; Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
var query = "SELECT [Reference No_] FROM [RMS2015].[dbo].[RMS Live$Artwork Brief] WHERE [No_] = " + argclean + " ";

上面是我尝试过的代码,但我似乎无法让它工作

1 个答案:

答案 0 :(得分:0)

养成在查询中使用params的习惯会更好,例如:

var query = "SELECT [Reference No_] FROM [RMS2015].[dbo].[RMS Live$Artwork Brief] WHERE [No_] = @ArtworkNumber;

......然后:

new SqlParameter()
{
    ParameterName = "@ArtworkNumber",
    SqlDbType = SqlDbType.VarChar,
    Value = argclean
}

更新

这是我用来从查询中检索DataTable的通用方法:

public static DataTable ExecuteSQLReturnDataTable(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
    using (DataSet ds = new DataSet())
    using (SqlConnection connStr = new SqlConnection(YourConnStr))
    using (SqlCommand cmd = new SqlCommand(sql, connStr))
    {
        cmd.CommandType = cmdType;
        cmd.CommandTimeout = EXTENDED_TIMEOUT;
        foreach (var item in parameters)
        {
            cmd.Parameters.Add(item);
        }

        cmd.Connection.Open();
        new SqlDataAdapter(cmd).Fill(ds);
        return ds.Tables[0];
    }
}

可以像这样调用:

DataTable dtDeliveryPerformanceResults = 
    SQLDBHelper.ExecuteSQLReturnDataTable(
        PLATYPUS_STOREDPROC,
        CommandType.StoredProcedure,
        new SqlParameter()
        {
            ParameterName = "@Unit",
            SqlDbType = SqlDbType.VarChar,
            Value = unit
        },
        new SqlParameter()
        {
            ParameterName = "@BeginDate",
            SqlDbType = SqlDbType.DateTime,
            Value = _begDate
        },
        new SqlParameter()
        {
            ParameterName = "@EndDate",
            SqlDbType = SqlDbType.DateTime,
            Value = _endDate
        },
        new SqlParameter()
        {
            ParameterName = "@PoisonToeLength",
            SqlDbType = Convert.ToInt32(SqlDbType.Int),
            Value = 42
        }
    );

该示例显示调用存储过程(推荐的做法),但您可以将其用于"常规"或"普通香草" SQL查询也是如此。