使用Merge语句继续此示例 http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/
我试图理解为什么在最终结果中(合并之后),StudentID 4显示在结果BEFORE StudentID 3之前。是的,我知道我可以订购结果,但我很好奇默认情况是在这里工作。请参阅下面的代码,以及结果之前/之后。有人可以解释一下吗?
USE AdventureWorks2012
GO
CREATE TABLE StudentDetails
(
StudentID INTEGER PRIMARY KEY,
StudentName VARCHAR(15)
)
GO
INSERT INTO StudentDetails
VALUES(1,'SMITH')
INSERT INTO StudentDetails
VALUES(2,'ALLEN')
INSERT INTO StudentDetails
VALUES(3,'JONES')
INSERT INTO StudentDetails
VALUES(4,'MARTIN')
INSERT INTO StudentDetails
VALUES(5,'JAMES')
GO
--SELECT * FROM dbo.StudentDetails
CREATE TABLE StudentTotalMarks
(
StudentID INTEGER REFERENCES StudentDetails,
StudentMarks INTEGER
)
GO
INSERT INTO StudentTotalMarks
VALUES(1,230)
INSERT INTO StudentTotalMarks
VALUES(2,255)
INSERT INTO StudentTotalMarks
VALUES(3,200)
GO
-- see results before Merge
SELECT * FROM dbo.StudentTotalMarks
StudentID StudentMarks
1 230
2 255
3 200
现在我们进行合并
MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);
GO
-- see results after MERGE
SELECT * FROM dbo.StudentTotalMarks
StudentID StudentMarks
1 255
4 25
3 225
5 25
答案 0 :(得分:0)
绝对没有隐式排序顺序!!
插入数据的顺序无关紧要。它可能会像这样回归。所以 - 到目前为止 - 排序是随机。
另一种选择是使用ROW_NUMBER() OVER(ORDER BY col)
(或... OVER(ORDER BY...)
的其他函数),它将返回一个排序的结果集(如果它在一个唯一键之后排序,并且你不使用多个函数进行排序效果)。
查找详细信息here: General Remarks
但是:确保某种排序顺序的唯一方法是ORDER BY
到最外面的SELECT
。