2
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 与数据库中列的最新可用日期进行比较,而不是今天的日期。您看到的代码工作正常,但是当我选择比数据库中最后一个现有日期更晚的日期时,查询会运行一段时间,然后返回未找到任何列的错误。

提前感谢您的任何建议。

帮助。以下部分代码不起作用,但我不知道为什么。有没有人有什么建议?谢谢

     -- 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
4

2 回答 2

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).

于 2013-02-14T13:30:28.930 回答
1

尝试这个...

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

IF @StartDate <= @maxDate
BEGIN
  --Your original query here
END
于 2013-02-14T13:34:00.950 回答