我尝试通过选择查询来获取@MechanicExpertTable
表的全名,但会得到错误
关键字“ SELECT”附近的语法不正确。
我的代码:
DECLARE @MechanicExpertTable AS TABLE
(
Id INT,
FirstName NVARCHAR(128),
LastName NVARCHAR(128)
);
INSERT INTO @MechanicExpertTable
SELECT
PROFILE.Id,
PROFILE.FirstName,
PROFILE.LastName
FROM
EstimatedRialMechanicExpert
INNER JOIN
PROFILE ON EstimatedRialMechanicExpert.ProfileId = PROFILE.Id
WHERE
EstimatedRialId = @id
DECLARE @MechanicExpert1 NVARCHAR(128) =
SELECT TOP(1)
ROW_NUMBER() OVER(ORDER BY Id ASC) AS rownumber,
@MechanicExpertTable.FirstName + ' ' + @MechanicExpertTable.LastName
FROM
@MechanicExpertTable
WHERE
rownumber = 3
该如何解决?
答案 0 :(得分:3)
如果要获取某个特定位置的全名,请尝试以下示例。在您的情况下,使用ROW_NUMBER()
而不使用PARTITION BY
,因此TOP(1)
是不必要的。
输入:
DECLARE @MechanicExpertTable AS TABLE (
Id INT,
FirstName NVARCHAR(128),
LastName NVARCHAR(128)
);
INSERT INTO @MechanicExpertTable
(Id, FirstName, LastName)
VALUES
(1, 'FirstName1', 'LastName1'),
(2, 'FirstName2', 'LastName2'),
(6, 'FirstName6', 'LastName6'),
(7, 'FirstName7', 'LastName7'),
(9, 'FirstName9', 'LastName9')
T-SQL:
DECLARE @MechanicExpert1 NVARCHAR(128)
SELECT TOP(1) @MechanicExpert1 = FullName
FROM (
SELECT
ROW_NUMBER() OVER(ORDER BY Id ASC) AS rownumber,
FirstName + ' ' + LastName AS FullName
FROM @MechanicExpertTable
) t
WHERE rownumber = 3
PRINT @MechanicExpert1
输出:
FirstName6 LastName6
答案 1 :(得分:1)
缺少括号。为您的子查询添加(),并且代码应如下所示-
DECLARE @MechanicExpert1 NVARCHAR(128) =
(
SELECT TOP 1 T
FROM
(
SELECT ROW_NUMBER() OVER(ORDER BY Id ASC) AS rownumber,
@MechanicExpertTable.FirstName + ' ' + @MechanicExpertTable.LastName AS T
FROM @MechanicExpertTable
)A WHERE rownumber = 3
)
注意:由于您的脚本中提供了TOP 1,因此我已在选择中添加了TOP 1。基本上,当您使用RowNumber = 3进行过滤时,没有机会出现多行。您可以从脚本中删除“ TOP 1”。