如何使用身份增加行 ID 以关闭

How to incement row id with identity to off

我在 select 时收到此错误。

DECLARE @TopID INT
SELECT @TopID = MAX([QuestionId]) from [SurveyQuestions];

 SELECT
       @TopID = @TopID + 1   
       ,[questiontext]
      ,[DeptID]
      ,[SurveyID]   
  FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

我知道可以通过将身份设置为 ON.but 来修复此错误,我不希望这样,因为我的数据库托管在 legecy 应用程序中,更改此设置会破坏其他内容。

这与身份无关。它与 select 有关。你有:

  SELECT  @TopID = @TopID + 1, 
         [questiontext], [DeptID], [SurveyID]   
  FROM [SOSS].[dbo].[SurveyQuestions]
  WHERE surveyid = 80

它有一个赋值 它 returns 值。我想你真的想要:

  SELECT @TopId + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) as rownum, 
         [questiontext], [DeptID], [SurveyID]   
  FROM [SOSS].[dbo].[SurveyQuestions]
  WHERE surveyid = 80;

注意:如果您确实想要特定顺序的结果,请将 ORDER BY both 添加到查询和 ROW_NUMBER()

这就是您 selecting 的方式,您不能在 select 中使用运算符来获取其他列。请参阅此 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

SQL Fiddler

另一种选择,结合您的 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

SQL Fiddler