我在SQL Server 2008中运行以下查询,该查询将在01/01/2014之后返回数据项。
如何更改查询以提示执行日期范围,以便我可以在特定日期之间返回数据?我最终希望将其创建为数据库视图并通过MS Excel运行查询。
SELECT J_CODATE as Typed_Date,
J_CRDATE as Created_Date,
J_AUTHOR as Author_Id,
CAST(A_FNAME + ' ' + A_SURNAME AS NVARCHAR) AS Author_Name,
J_JNUMBER as Job_Number,
J_SRSTATUS as SR_Status,
J_LENGTH as Job_Length,
J_TRANTIME as Typing_Time,
J_TRANS as Typist_id,
CAST(T_FNAME + ' ' + T_SURNAME AS NVARCHAR) AS Typist_Name,
CAST(J_TRANTIME AS FLOAT) / CAST(Job.J_LENGTH AS FLOAT) AS Productivity_Factor
FROM author, job, trans
WHERE J_CODATE >= '2014-01-01 00:00:00'
and J_LENGTH > 0 and J_TRANTIME > 1 and J_SRSTATUS > 0
and (Cast(J_LENGTH as Float) / Cast(J_TRANTIME as Float)) < 2
and (Cast(J_TRANTIME as Float) / Cast(J_LENGTH as Float)) < 20
and Job.J_TRANS = Trans.T_ID
and Job.J_AUTHOR = author.A_ID
ORDER BY J_CODATE desc
由于
答案 0 :(得分:0)
那么您的目标是通过Excel访问数据库数据,并让Excel提示您输入参数?
无法将构建到查询中提示您输入参数的功能。提示出现在哪里 - 在服务器的屏幕上?如果执行查询的程序是Windows服务或其他没有UI的进程,会发生什么?
您可以在MS Access中执行此操作,因为Access既是数据库又是用于操作该数据库的UI。但即使在Access中,如果Access可执行文件以外的应用程序试图使用数据库,则不会在该程序中提示参数:如果参数不是,则只会出现异常在程序尝试执行查询时提供。
所以这至少是Excel问题的一半。我不确定Excel的数据工具是否包含提示您输入参数的功能,尽管我希望它可以。但你必须对此进行研究。
要解决问题的SQL Server部分:参数化查询的最简单方法可能是创建一个存储过程,Excel将通过其数据工具为您执行。它看起来像这样:
CREATE PROCEDURE dbo.TestProcedure
(
@StartDate datetime,
@EndDate datetime
)
AS
SELECT J_CODATE as Typed_Date,
J_CRDATE as Created_Date,
J_AUTHOR as Author_Id,
CAST(A_FNAME + ' ' + A_SURNAME AS NVARCHAR) AS Author_Name,
J_JNUMBER as Job_Number,
J_SRSTATUS as SR_Status,
J_LENGTH as Job_Length,
J_TRANTIME as Typing_Time,
J_TRANS as Typist_id,
CAST(T_FNAME + ' ' + T_SURNAME AS NVARCHAR) AS Typist_Name,
CAST(J_TRANTIME AS FLOAT) / CAST(Job.J_LENGTH AS FLOAT) AS Productivity_Factor
FROM author, job, trans
WHERE J_CODATE BETWEEN @StartDate and @EndDate
and J_LENGTH > 0 and J_TRANTIME > 1 and J_SRSTATUS > 0
and (Cast(J_LENGTH as Float) / Cast(J_TRANTIME as Float)) < 2
and (Cast(J_TRANTIME as Float) / Cast(J_LENGTH as Float)) < 20
and Job.J_TRANS = Trans.T_ID
and Job.J_AUTHOR = author.A_ID
ORDER BY J_CODATE desc
如果它看起来很像你的查询,那是因为它是:除了将它包装在存储过程中之外,我将你使用的日期文字转换为参数@StartDate
和@EndDate
,因为你说你想要一个日期范围。