我有一个带有列的简单表 - id,name和salary。
我希望使用存储过程获取id的名称,工资和年薪。
我想过创建一个这样的简单存储过程:
CREATE PROCEDURE spGetDetails
@id int,
@annualSal int out
AS
BEGIN
SELECT
name, salary,
@annualSal = (salary * 12)
FROM
tblPrac
WHERE
id = @id
END
但是我收到了一个错误:
为变量赋值的SELECT语句不能与数据检索操作结合使用
如果已经问过这个qs,请给我链接,我会删除这个qs。我搜索了但我想我错过了关键词。感谢
答案 0 :(得分:2)
您不需要OUTPUT
参数。您可以像这样查询 -
CREATE PROCEDURE spGetDetails
@id int
AS
BEGIN
SET NOCOUNT ON
SELECT Name, Salary, (Salary*12) AS AnnualSalary FROM tblPrac WHERE id = @id
END
答案 1 :(得分:0)
你有混合的东西,所以你需要在两种可能性之间进行选择
CREATE PROCEDURE spGetDetails
@id int,
@name varchar(100) out,
@salary decimal(16,2) out,
@annualSal decimal(16,2) out
AS
BEGIN
set nocount on
SELECT @name = name,
@salary = salary,
@annualSal = (salary * 12)
FROM tblPrac
WHERE id = @id
END
或者
CREATE PROCEDURE spGetDetails
@id int
AS
BEGIN
set nocount on
SELECT name,
salary,
(salary * 12) as anualSal
FROM tblPrac
WHERE id = @id
END
答案 2 :(得分:-1)
您需要存储数据并分离操作(正如错误消息所解释的那样):
CREATE PROCEDURE spGetDetails
(
@id int,
@annualSal int out
)
AS
BEGIN;
SET NOCOUNT ON;
DECLARE @DataSource TABLE
(
[name] VARCHAR(12)
,[salary] DECIMAL(9,2)
);
INSERT INTO @DataSource ([name], [salary])
SELECT name, salary
FROM tblPrac
WHERE id = @id;
SELECT [name]
,[salary]
FROM @DataSource;
SELECT @annualSal = 12 * [salary]
FROM @DataSource;
SET NOCOUNT OFF;
RETURN;
END;