将查询转换为存储过程

时间:2013-06-21 14:50:12

标签: sql sql-server tsql sql-server-2005 stored-procedures

我有以下查询按原样运行(人们可能会畏缩,但试着忽略它有多糟糕):

DECLARE @submit_day DATETIME;
DECLARE @meeting_day DATETIME;
DECLARE @start_time_of_business_day DATETIME;
DECLARE @business_day_hours FLOAT;
DECLARE @submit_time DATETIME;
DECLARE @meeting_time DATETIME;
DECLARE @num1 FLOAT
DECLARE @num2 FLOAT
DECLARE @num3 FLOAT

SET @meeting_day = '2013-06-24';  -- USER GENERATED VARIABLE
SET @meeting_time = '15:45'; -- USER GENERATED

SET @submit_day = CONVERT(VARCHAR(10),GETDATE(),101);
SET @submit_time =  CONVERT(VARCHAR(8),GETDATE(),108);

SET @start_time_of_business_day = '09:00';
SET @business_day_hours = 8.5;

SET @num1 = ((DATEDIFF(dd, @submit_day, @meeting_day))
-(DATEDIFF(wk, @submit_day, @meeting_day) * 2)
-(CASE WHEN DATEPART(dw, @submit_day) = 1 THEN 1 ELSE 0 END)
-(CASE WHEN DATEPART(dw, @meeting_day) = 7 THEN 1 ELSE 0 END)
-(SELECT COUNT(*) FROM intranet.dbo.bank_holiday WHERE the_date BETWEEN @submit_day AND @meeting_day)) * @business_day_hours
SET @num2 = (select datediff(minute, @start_time_of_business_day, @submit_time)) / 60.0
SET @num3 = (select datediff(minute, @start_time_of_business_day, @meeting_time)) / 60.0

select @num1 - @num2 + @num3 as [hours]

所以我想把它设置为存储过程,所以我尝试了以下内容:

USE [INTRANET]
GO
/****** Object:  StoredProcedure [dbo].[BusinessHours]    Script Date: 06/21/2013 15:19:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[BusinessHours]

@meeting_date DATETIME,
@meeting_time DATETIME

AS

DECLARE @submit_day DATETIME;
DECLARE @submit_time DATETIME;

DECLARE @start_time_of_business_day DATETIME;
DECLARE @business_day_hours FLOAT;

DECLARE @num1 FLOAT
DECLARE @num2 FLOAT
DECLARE @num3 FLOAT

SET @submit_day = CONVERT(VARCHAR(10),GETDATE(),101);
SET @submit_time =  CONVERT(VARCHAR(8),GETDATE(),108);

SET @start_time_of_business_day = '09:00';
SET @business_day_hours = 8.5;

SET @num1 = ((DATEDIFF(dd, @submit_day, @meeting_day))
-(DATEDIFF(wk, @submit_day, @meeting_day) * 2)
-(CASE WHEN DATEPART(dw, @submit_day) = 1 THEN 1 ELSE 0 END)
-(CASE WHEN DATEPART(dw, @meeting_day) = 7 THEN 1 ELSE 0 END)
-(SELECT COUNT(*) FROM intranet.dbo.bank_holiday WHERE the_date BETWEEN @submit_day AND @meeting_day)) * @business_day_hours
SET @num2 = (select datediff(minute, @start_time_of_business_day, @submit_time)) / 60.0
SET @num3 = (select datediff(minute, @start_time_of_business_day, @meeting_time)) / 60.0

select @num1 - @num2 + @num3 as [hours]

这给了我一个错误:

  

Msg 137,Level 15,State 2,Procedure BusinessHours,25行   必须声明标量变量“@meeting_day”   Msg 137,Level 15,State 2,Procedure BusinessHours,29号线   必须声明标量变量“@meeting_day”。

尝试搜索,但无法弄清楚如何让它发挥作用。

2 个答案:

答案 0 :(得分:2)

是。您已将DECLARE d变量@meeting_day重命名为参数@meeting_date

修复此问题。

答案 1 :(得分:1)

您在参数声明中键入了“meeting_date”而不是“meeting_day”。

CREATE PROCEDURE [dbo].[BusinessHours]

@meeting_day DATETIME, --ERROR IS HERE
@meeting_time DATETIME

AS