如何在存储过程中插入顶部选择数字作为参数
How to insert top selecting number as a parameter in a stored procedure
我试图不时获得 table 的前 10、前 5 记录。所以我要创建一个存储过程,其参数接受记录数作为参数。但它在查询中@number 附近给我一个错误。
这是我尝试过的,这给了我一个语法错误:
error=Msg 102, Level 15, State 1, Procedure selectVoterTopGivenNumberRECS, Line 10 Incorrect syntax near '@number'.
代码:
CREATE PROCEDURE selectVoterTopGivenNumberRECS
(
@number int
)
AS
BEGIN
BEGIN TRANSACTION
SET NOCOUNT ON;
--Query
SELECT TOP @number
V.NICorPP as NICorPP,V.fName+' '+V.mName+' '+V.lName AS Name,
V.DOB AS DateofBirth,
CASE (V.gender)
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
END AS Gender,V.vtaddress AS VoterAddress,V.phHome AS ContactHome,
V.phMob AS ContactMobile,V.occupation AS Occupation,
V.occRegID AS RegisteredOCCID,LGD.LGDivName
FROM Voter V
INNER JOIN LGDivision LGD ON V.lgDiv=LGD.LGDivID
WHERE V.vtStatus='Active';
COMMIT TRANSACTION
END;
如何克服这个问题?
您需要在 parameter
两边加上括号
SELECT TOP (@number) V.NICorPP AS NICorPP,
V.fName + ' ' + V.mName + ' ' + V.lName AS NAME,
V.DOB AS DateofBirth,
CASE V.gender
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
END AS Gender,
V.vtaddress AS VoterAddress,
V.phHome AS ContactHome,
V.phMob AS ContactMobile,
V.occupation AS Occupation,
V.occRegID AS RegisteredOCCID,
LGD.LGDivName
FROM Voter V
INNER JOIN LGDivision LGD
ON V.lgDiv = LGD.LGDivID
WHERE V.vtStatus = 'Active';
你只需要给变量添加参数,改变
SELECT TOP @number
为了
SELECT TOP (@number)
我试图不时获得 table 的前 10、前 5 记录。所以我要创建一个存储过程,其参数接受记录数作为参数。但它在查询中@number 附近给我一个错误。
这是我尝试过的,这给了我一个语法错误:
error=Msg 102, Level 15, State 1, Procedure selectVoterTopGivenNumberRECS, Line 10 Incorrect syntax near '@number'.
代码:
CREATE PROCEDURE selectVoterTopGivenNumberRECS
(
@number int
)
AS
BEGIN
BEGIN TRANSACTION
SET NOCOUNT ON;
--Query
SELECT TOP @number
V.NICorPP as NICorPP,V.fName+' '+V.mName+' '+V.lName AS Name,
V.DOB AS DateofBirth,
CASE (V.gender)
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
END AS Gender,V.vtaddress AS VoterAddress,V.phHome AS ContactHome,
V.phMob AS ContactMobile,V.occupation AS Occupation,
V.occRegID AS RegisteredOCCID,LGD.LGDivName
FROM Voter V
INNER JOIN LGDivision LGD ON V.lgDiv=LGD.LGDivID
WHERE V.vtStatus='Active';
COMMIT TRANSACTION
END;
如何克服这个问题?
您需要在 parameter
SELECT TOP (@number) V.NICorPP AS NICorPP,
V.fName + ' ' + V.mName + ' ' + V.lName AS NAME,
V.DOB AS DateofBirth,
CASE V.gender
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
END AS Gender,
V.vtaddress AS VoterAddress,
V.phHome AS ContactHome,
V.phMob AS ContactMobile,
V.occupation AS Occupation,
V.occRegID AS RegisteredOCCID,
LGD.LGDivName
FROM Voter V
INNER JOIN LGDivision LGD
ON V.lgDiv = LGD.LGDivID
WHERE V.vtStatus = 'Active';
你只需要给变量添加参数,改变
SELECT TOP @number
为了
SELECT TOP (@number)