C# 假设字符串SQL操作中的行顺序
我有一个存储过程,需要假设行顺序始终相同,以便正确运行,否则我将得到错误的数据。用户提供需要查询的ID字符串,存储过程使用该字符串将这些字符串放入表中_SPLIT@Parameter“,”操作 假设字符串将按照给定给表的顺序放入表中,安全吗?我创建了一个单元测试并运行了10000次,每次都检查表的顺序,结果通过了。因此,从这一点来看,我猜测做出这样的假设是安全的 SQL: C语言中的单元测试C# 假设字符串SQL操作中的行顺序,c#,sql,stored-procedures,ssms,C#,Sql,Stored Procedures,Ssms,我有一个存储过程,需要假设行顺序始终相同,以便正确运行,否则我将得到错误的数据。用户提供需要查询的ID字符串,存储过程使用该字符串将这些字符串放入表中_SPLIT@Parameter“,”操作 假设字符串将按照给定给表的顺序放入表中,安全吗?我创建了一个单元测试并运行了10000次,每次都检查表的顺序,结果通过了。因此,从这一点来看,我猜测做出这样的假设是安全的 SQL: C语言中的单元测试 [TestMethod] public void SQLOrderTest() { // Arr
[TestMethod]
public void SQLOrderTest()
{
// Arrange
string testIds = "3, 5, 1, 10";
string spName = "[dbo].[sp_TestOrder]";
string ServerName = PARR_DBDataObject.ServerName;
string DBName = PARR_DBDataObject.DBName;
// Act
bool results = true;
for(int i = 0; i < 10000; i++)
{
DataTable dt = SQL.QueryStoredProcedure(spName, DBName, ServerName, false, 5000,
new Tuple<string, object>("@TestIDs", testIds));
// First Row
if (GetRowNumber(dt, "3") != 1) results = false;
// Second Row
if (GetRowNumber(dt, "5") != 2) results = false;
// Third Row
if (GetRowNumber(dt, "1") != 3) results = false;
// Forth Row
if (GetRowNumber(dt, "10") != 4) results = false;
}
Assert.AreEqual(results, true);
}
private int GetRowNumber(DataTable dt, string TestIDValue)
{
var row = from r in dt.AsEnumerable()
where r.Field<string>("TestIDs") == TestIDValue
select new
{
TestID = r.Field<string>("TestIDs"),
rowNum = r.Field<Int32>("RowNumber")
};
return row.First().rowNum;
}
SQL表表示无序集。假设数据是按特定顺序排列从来都不是一个好主意,除非您使用ORDERBY。通常,单个页面上的小数据集甚至会像您期望的那样一致地排序。但使用记录为不正确的功能仍然是危险的
如果要保证排序,则可以插入带有order by和ordering值的记录。以下是使用递归CTE的方法:
with cte as (
select convert(varchar(max), left(@testids, charindex(',', @testids + ',') - 1)) as id,
convert(varchar(max), stuff(@testids, 1, charindex(',', @testids + ','), '')) as rest,
1 as lev
union all
select convert(varchar(max), left(rest, charindex(',', rest + ',') - 1)) as id,
convert(varchar(max), stuff(rest, 1, charindex(',', rest + ','), '')),
lev + 1 as lev
from cte
where rest <> ''
)
select trim(id) as id, lev
into #testnames
from cte
where trim(id) <> ''
order by lev; -- not really needed but handy if you have an identity column
SQL Server是多线程的,数据可以随机保存和读取。要始终以相同的顺序获取数据,唯一的方法是使用order BY。如果您需要检索特定顺序的数据,请不要添加带有序列号的列。感谢您的解释,即使使用我的小表,我也不会使用这种假设。
with cte as (
select convert(varchar(max), left(@testids, charindex(',', @testids + ',') - 1)) as id,
convert(varchar(max), stuff(@testids, 1, charindex(',', @testids + ','), '')) as rest,
1 as lev
union all
select convert(varchar(max), left(rest, charindex(',', rest + ',') - 1)) as id,
convert(varchar(max), stuff(rest, 1, charindex(',', rest + ','), '')),
lev + 1 as lev
from cte
where rest <> ''
)
select trim(id) as id, lev
into #testnames
from cte
where trim(id) <> ''
order by lev; -- not really needed but handy if you have an identity column
select tn.*
from #testnames tn
order by lev;