我在选择时收到此错误。
DECLARE @TopID INT
SELECT @TopID = MAX([QuestionId]) from [SurveyQuestions];
SELECT
@TopID = @TopID + 1
,[questiontext]
,[DeptID]
,[SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80
为变量赋值的SELECT语句不能是 结合数据检索操作。
我知道在将身份设置为ON时可以修复此错误。但我不希望这样,因为我的数据库托管在legecy应用程序中,更改此设置会使其他事情中断。
答案 0 :(得分:3)
这与身份无关。它与select
有关。你有:
SELECT @TopID = @TopID + 1,
[questiontext], [DeptID], [SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions]
WHERE surveyid = 80
这有一个赋值和它返回值。我想你真的想要:
SELECT @TopId + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) as rownum,
[questiontext], [DeptID], [SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions]
WHERE surveyid = 80;
注意:如果您确实希望按特定顺序排列结果,请将ORDER BY
两者添加到查询和ROW_NUMBER()
。
答案 1 :(得分:1)
这是您选择的方式,您无法在选择其他列时使用运算符。请参阅此link,了解您做错了什么。
我认为你真正需要的是:
DECLARE @TopID INT
SELECT @TopID = MAX([QuestionId]) from [SurveyQuestions];
SELECT
@TopID + 1
,[questiontext]
,[DeptID]
,[SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80
编辑:
或者基于ROW_NUMBER
的解决方案,如:
DECLARE @TopID INT
SELECT @TopID = MAX([QuestionId]) from [SurveyQuestions];
SELECT
@TopID + ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as TopID
,[questiontext]
,[DeptID]
,[SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80
改善先前答案的一点(合并为一个查询):
SELECT (
SELECT TOP 1 QuestionId
FROM SurveyQuestions
ORDER BY QuestionId DESC
)
+ ROW_NUMBER() OVER ( ORDER BY (SELECT 1)) AS TopID
, [questiontext], [DeptID], [SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions]
WHERE surveyid = 80
另一种选择,梳理您的2个查询:
SELECT
(SELECT MAX(ID) FROM ForgeRock) as MAx_Id
, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as Row_ID,
(SELECT TOP 1 ID FROM ForgeRock ORDER BY Id DESC) +
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as New_Id,
productName,
description
FROM
ForgeRock