【问题标题】:SQL Server syntax correction [closed]SQL Server 语法更正 [关闭]
【发布时间】:2021-07-20 01:47:49
【问题描述】:

我正在尝试创建 SQL Server 存储过程,但出现了一些错误。

create procedure testproc8
as
begin
    declare @x int 
    declare @z int
    declare @y money OUTPUT

    set @y = (select (sum([OrderQty] * [UnitPrice]) / sum([OrderQty])) * @x
              from [dbo].[Transactions]
              where [ProductID] = @z
              group by [ProductID])

    return 
end

以下是错误:

消息 102,级别 15,状态 1,过程 testproc8,第 6 行 [批处理开始第 60 行]
'OUTPUT' 附近的语法不正确

消息 137,级别 15,状态 1,过程 testproc8,第 7 行 [批处理开始第 60 行]
必须声明标量变量“@y”

提前致谢

【问题讨论】:

  • 我认为这是针对 MS SQL Server 的;它是否正确?请始终指定数据库供应商,因为“SQL”太通用了
  • 您是否打算在执行过程时将参数传递给您的过程?或者您是否打算通过程序中的代码设置局部变量的值?你想要一个多于 1 行的结果集还是只有 1 个单一的总和作为输出?
  • 是的,我计划将 x 和 z 作为参数...结果只有一个 num

标签: sql sql-server ssms


【解决方案1】:

删除 Output 并为您的结果选择 @y

create proc testproc8
-- Add the parameters for the stored procedure here 
as
begin
declare @x int 
--set @x = certain integer 'if your stored procedure did not have parameters'
declare @z int
--set @z = certain integer 'if your stored procedure did not have parameters'
declare @y money 
set @y = 
(
    select (SUM([OrderQty]*[UnitPrice])/SUM([OrderQty])) * @x
    from [dbo].[Transactions]
    where [ProductID] = @z
    group by [ProductID]
)

select @y
end

【讨论】:

  • 根本不需要@y,你可以只需要select
【解决方案2】:

试试这个代码:

CREATE PROCEDURE testproc8
@x AS INT,
@z AS INT
AS
BEGIN

DECLARE @y money

set @y = (
    select (SUM([OrderQty]*[UnitPrice])/SUM([OrderQty])) * @x
    from [dbo].[Transactions]
    where [ProductID] = @z
    group by [ProductID]
)

SELECT @y

END

【讨论】:

  • 请解释你的答案。代码只有答案,不会很容易理解。
猜你喜欢
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 2021-04-15
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2013-06-26
相关资源
最近更新 更多