2012-01-04 121 views
1

這個問題是繼續努力編寫我的第一個cte,我在其他一些最近的帖子中提到過。簡而言之,我正在爲下面的查詢編寫一些編譯器錯誤。我現在收到錯誤「Subquery返回了多個值,當子查詢跟隨=,!=,<,< =,>,> =或當子查詢用作表達式時,這是不允許的。但是根據我目前的能力,我認爲下面的內容對我來說似乎是「合法的」......任何幫助都會很棒。順便說一句,我不是得到這個錯誤,或Visual Studio 2010中關閉,當我嘗試運行此...Sql Server cte錯誤「子查詢返回了多個值。」

WITH Symb AS 
(
    SELECT Symbol 
    FROM tblSymbolsMain 
), 

DatesNotNeeded AS 
(
    SELECT Date 
    FROM tblDailyPricingAndVol inner join Symb on 
     tblDailyPricingAndVol.Symbol = Symb.Symbol 
), 

WideDateRange AS 
(
    SELECT TradingDate 
    FROM tblTradingDays 
    WHERE (TradingDate >= dbo.NextAvailableDataDownloadDateTime()) AND (TradingDate <= dbo.LatestAvailableDataDownloadDateTime()) 
), 

DatesNeeded AS 
(
    SELECT TradingDate 
    FROM WideDateRange wdr 
    WHERE NOT EXISTS (SELECT * FROM DatesNotNeeded d where d.Date = wdr.TradingDate) 
) 

SELECT Symb.Symbol, DatesNeeded.TradingDate 
FROM Symb CROSS JOIN DatesNeeded 

我的功能,要求:

ALTER FUNCTION dbo.LatestAvailableDataDownloadDateTime() 
    RETURNS date 
BEGIN 
    RETURN (SELECT DATEADD(hour, 18, MAX(TradingDate)) AS LatestTradingDateAvailForDL 
    FROM tblTradingDays 
    GROUP BY TradingDate 
    HAVING (DATEADD(hour, 18, MAX(TradingDate)) < GETDATE())) 
END 

ALTER FUNCTION dbo.NextAvailableDataDownloadDateTime() 
    RETURNS date 
BEGIN 
    RETURN (SELECT DATEADD(hour, 18, MIN(TradingDate)) AS TrDate 
    FROM tblTradingDays 
    HAVING (DATEADD(hour, 18, MIN(TradingDate)) > dbo.LatestDataDownloadDate())) 
END 
+0

您可以發佈背後'NextAvailableDataDownloadDateTime'和'LatestAvailableDataDownloadDateTime'的代碼? – Eric 2012-01-04 22:18:23

+0

@Eric Yup,剛纔.. – StatsViaCsh 2012-01-04 22:23:14

+0

@StatsViaCash - 發現問題。你正在試圖找到最大值的列。這將只返回'dateadd(hour,18,tradingdate) Eric 2012-01-04 22:28:22

回答

2

你的函數返回多個值。試試這個:

ALTER FUNCTION dbo.LatestAvailableDataDownloadDateTime() 
    RETURNS date 
BEGIN 
    RETURN (SELECT DATEADD(hour, 18, MAX(TradingDate)) AS LatestTradingDateAvailForDL 
    FROM tblTradingDays 
    WHERE (DATEADD(hour, 18, TradingDate) < GETDATE())) 
END 

和:

ALTER FUNCTION dbo.NextAvailableDataDownloadDateTime() 
    RETURNS date 
BEGIN 
    RETURN (SELECT DATEADD(hour, 18, MIN(TradingDate)) AS TrDate 
    FROM tblTradingDays 
    WHERE (DATEADD(hour, 18, TradingDate) > dbo.LatestDataDownloadDate())) 
END 
+0

從第一對夫妻關卡開始,我認爲我們是在做生意。 :)今天晚上,我正在換出當前讀取的SQL Server書籍。謝謝。 – StatsViaCsh 2012-01-04 22:38:38

-2

你再選擇有選擇*它返回所有列。子查詢需要處理一列和行,即:
從汽車選擇cartype其中cartype =「本田」

好運, speeves

+1

它存在於'不存在'中 - 這不是問題。您可以將多個列返回到「exists」。 – Eric 2012-01-04 22:17:49

+0

謝謝,埃裏克!我一直在學習。我沒有看到EXISTS:P – speeves 2012-01-05 03:27:18