我在 C# 中使用 t-sql 选择查询时遇到了一些问题。查询如下:
@"SELECT * FROM
(SELECT *, ROW_NUMBER() OVER (ORDER BY id) as row_number
FROM [mytable]) t0
WHERE row_number BETWEEN @skip and @take
AND
uploadDate IN (@years)
AND NOT photoId IN (@shownPhotos)
ORDER BY NEWID()";
cmd.Parameters.Add("@skip", SqlDbType.Int).Value = skip;
cmd.Parameters.Add("@take", SqlDbType.Int).Value = take;
cmd.Parameters.Add("@shownPhotos", SqlDbType.VarChar).Value = shownPhotos;
cmd.Parameters.Add("@years", SqlDbType.VarChar).Value = years;
该方法有四个参数:skip count、take count、showedPhotos(逗号分隔的字符串,包含照片 ID)、years(逗号分隔的字符串,包含显示照片的年份)
所以基本上我希望它从我的数据库中返回与逗号分隔字符串中的任何年份相匹配且尚未显示的照片。
问题(我认为)是我的参数是字符串,因此它们被解释为“1234,567,890”和“2011,2012”。在没有 ' 的 SQL 服务器管理工具中运行查询时,它工作正常。
有人有解决方法吗?:-)
提前非常感谢!
更新代码:
// Create datatables
DataTable yearsTable = new DataTable();
yearsTable.Columns.Add("YearID", typeof(string));
yearsTable.Columns.Add("Year", typeof(string));
foreach(string year in years.Split(','))
yearsTable.Rows.Add(new object[] { year, year });
using (var conn = new SqlConnection(GlobalSettings.DbDSN))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"SELECT * FROM
(SELECT *, ROW_NUMBER() OVER (ORDER BY id) as row_number
FROM [mytable]) t0
WHERE row_number BETWEEN @skip and @take
AND
uploadedDate IN (@years)
ORDER BY NEWID()";
SqlParameter skipParam = cmd.Parameters.AddWithValue("@skip", skip);
skipParam.SqlDbType = SqlDbType.Int;
SqlParameter takeParam = cmd.Parameters.AddWithValue("@take", take);
takeParam.SqlDbType = SqlDbType.Int;
SqlParameter yearsParam = cmd.Parameters.AddWithValue("@years", yearsTable);
yearsParam.SqlDbType = SqlDbType.Structured;
yearsParam.TypeName = "dbo.MyTableType";
var reader = cmd.ExecuteReader();
}