我有一个简单的存储过程,我想在公式中使用输出。
我的存储过程如下:
USE [MGCustom]
GO
/****** Object: StoredProcedure [dbo].[stpGetCogAmt] Script Date: 4/10/2019 4:55:17 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Mike Ruoppoli
-- Create date:
-- Description: <Procedure to get the Cogs value based on the month,Values to be included in a table later.>
-- =============================================
ALTER PROCEDURE [dbo].[stpGetCogAmt]
-- Add the parameters for the stored procedure here
@ProdMonth int
, @CogsRate DECIMAL(4,4) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--@CogsPerLb, @p2
Set @CogsRate =(CASE @ProdMonth
WHEN 1 THEN 0.0957 WHEN 2 THEN 0.0904 WHEN 3 THEN 0.0884 WHEN 4 THEN 0.0906 WHEN 5 THEN 0.0818 WHEN 6 THEN 0.0787 WHEN 7 THEN 0.0777 WHEN 8 THEN 0.0769 WHEN 9 THEN 0.0756 WHEN 10 THEN 0.0778
WHEN 11 THEN 0.0754 WHEN 12 THEN 0.0787 ELSE .08 END)
END
存储过程运行并按预期返回值,但是当我尝试在这种情况下使用时,我总是在'EXEC'附近得到错误的语法
更多代码
SELECT dbo.vwUD15.Date01, (EXEC dbo.stpGetCogAmt @ProdMonth = "(LEFT(dbo.vwUD15.Key2, LEN(dbo.vwUD15.Key2) - 5))") AS CogsRate
FROM dbo.vwUD15
我进行了大量搜索,无法弄清楚我在做什么错。
我将在很多公式中使用此存储过程...
答案 0 :(得分:1)
代码中的注释之一指向一种更好的建模方法:
create table CogRates (
ProdMonth int not null,
CogsRate decimal(4,4) not null,
constraint PK_CogRates PRIMARY KEY (ProdMonth),
constraint CK_CogRates_Months CHECK (ProdMonth between 1 and 12)
)
go
insert into CogRates (ProdMonth,CogsRate) values
(1 ,0.0957),
(2 ,0.0904),
(3 ,0.0884),
(4 ,0.0906),
(5 ,0.0818),
(6 ,0.0787),
(7 ,0.0777),
(8 ,0.0769),
(9 ,0.0756),
(10,0.0778),
(11,0.0754),
(12,0.0787)
go
SELECT v.Date01, cg.CogsRate AS CogsRate
FROM dbo.vwUD15 v
inner join
CogRates cg
on cg.ProdMonth = LEFT(v.Key2, LEN(v.Key2) - 5)
当基于集合的代码可以完成工作时,不要编写过程代码。
存储过程不能组成更大的查询。您可以将逻辑移到用户定义的函数中,但是当它基本上是 lookup 时,这就是SQL 擅长的事情。 (尽管最好不要在该比较的右侧对列的值进行操作)
通常,如果您正在考虑编写一个函数(而不是存储的proc),并且定义是确定性,而域是“ small”,则可以考虑使用表。另外,如果需要,您还可以免费获得函数的逆。