SQL在SP中选择maxDate

时间:2013-02-14 13:23:36

标签: sql sql-server sql-server-2008

USE [MyDatabase]
GO
Object:  StoredProcedure [dbo].[SP_MyProcedure]    
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_MyProcedure] 
-- Add the parameters for the stored procedure here
@StartDate  NVARCHAR(19),
@EndDate    NVARCHAR(19)
AS
BEGIN

SET NOCOUNT ON;

 Insert statements for procedure here
DECLARE @FirstQuery nvarchar(1500);
DECLARE @SecondQuery nvarchar(1500);
DECLARE @TSQL nvarchar(4000);



SET @FirstQuery =
    '
    SELECT * FROM OPENQUERY(LinkedServer,
    ''
    SELECT * FROM Server.Table
    WHERE Name IN 
    (SELECT Tagname COLLATE DATABASE_DEFAULT FROM LocalServer.MyServer.dbo."NameList"
    WHERE LOCATION = ''''X'''' AND SOURCE = ''''Y'''') AND TIMESTAMP >= ''''' + @StartDate + ''''' AND TIMESTAMP < ''''' + @EndDate + ''''''')';

我的问题是:如何在代码中包含max(date),因此@startDate将与DB中的列的最新可用日期进行比较,而不是今天的日期。 您看到的代码工作正常,但是当我选择比DB中最后一个现有日期更晚的日期时,查询会运行一段时间,然后才会返回没有找到列的错误。

提前感谢任何建议。

HELP。 以下部分代码不起作用,但我无法弄清楚原因。有没有人有什么建议?谢谢

     -- Insert statements for procedure here
DECLARE @FirstQuery nvarchar(1500);
DECLARE @SecondQuery nvarchar(1500);
DECLARE @TSQL nvarchar(4000);
DECLARE @MaxTimeStamp nvarchar(19);


SET@MaxTimeStamp =
'SELECT MAX(TimeStamp) From OPENQUERY(LinkedServer)'


IF @StartDate <= @MaxTimeStamp
BEGIN

SET @FirstQuery =
    '
    SELECT * FROM OPENQUERY(LinkedServer,
    ''
    SELECT * FROM Server.Table
    WHERE Name IN 
    (SELECT Tagname COLLATE DATABASE_DEFAULT FROM LocalServer.MyServer.dbo."NameList"
    WHERE LOCATION = ''''X'''' AND SOURCE = ''''Y'''') AND TIMESTAMP >= ''''' + @StartDate + ''''' AND TIMESTAMP < ''''' + @EndDate + ''''''')';

END

2 个答案:

答案 0 :(得分:2)

好吧,你可以用子查询替换它:

(select max(timestamp) from NameList)

如果这是一个存储过程,您可能希望将其放在变量中,例如:

declare @MaxTimestamp datetime;
select @MaxTimestamp = max(TimeStamp) from NameList

-- in your query, something like
      coalesce(@StartTime, maxTimeStamp)

如果性能存在问题,请尝试在NameList(Location, Source, Timestamp)上添加索引。

答案 1 :(得分:1)

试试这个......

DECLARE @maxDate datetime;
SELECT @maxDate = MAX(timestamp) FROM OPENQUERY(...);

IF @StartDate <= @maxDate
BEGIN
  --Your original query here
END