2012-02-18 70 views
3

所以我有這樣的工作是否正常:SQL Server 2008的列前綴錯誤

CREATE FUNCTION dbo.GetLiveStream(@UserName NVARCHAR(MAX)) RETURNS TABLE 
AS 
    RETURN (
    SELECT DISTINCT l.* 
     FROM StreamView l 
     JOIN Friendships f ON f.Sender = @UserName OR f.Recipient = @UserName 
    WHERE l.Sender <> @UserName 
     AND l.Recipient <> @UserName 
     AND ( l.Sender = f.Recipient 
      OR l.Sender = f.Sender 
      OR l.Recipient = f.Sender 
      OR l.Recipient = f.Recipient) 

) 
GO 

但嘗試做以下查詢時:

SELECT ROW_NUMBER() OVER(ORDER BY DateTime DESC) AS RowNumber, 
     * 
    FROM dbo.GetLiveStream('jason') 
    WHERE RowNumber >= 0 
    AND RowNumber < 0+ 10; 

我收到以下錯誤:

Msg 207, Level 16, State 1, Line 4
Invalid column name 'RowNumber'.
Msg 207, Level 16, State 1, Line 5
Invalid column name 'RowNumber'.

請注意,指定l.*將返回此錯誤:

Msg 107, Level 15, State 1, Line 2
The column prefix 'l' does not match with a table name or alias name used in the query.

GetLiveStream是一個函數:

RETURN (
    SELECT DISTINCT l.* 
     FROM StreamView l 
     JOIN Friendships f ON f.Sender = @UserName OR f.Recipient = @UserName 
    WHERE l.Sender <> @UserName 
     AND l.Recipient <> @UserName 
     AND ( l.Sender = f.Recipient 
      OR l.Sender = f.Sender 
      OR l.Recipient = f.Sender 
      OR l.Recipient = f.Recipient) AND f.IsPending = 0 

) 

這又如何解決?謝謝。

回答

4

您不能在WHERE子句中引用別名。這樣做:

select * 
from 
(
    SELECT ROW_NUMBER() OVER(ORDER BY DateTime DESC) AS RowNumber, 
      * 
     FROM dbo.GetLiveStream('jason') 
) a 
    WHERE RowNumber >= 0 
    AND RowNumber < 0+ 10; 

至於你l.*的錯誤,這是因爲該別名是本地的功能和它的查詢定義,不能在其外部引用。

-1

請勿在存儲過程或函數中使用*,因爲它會被編譯爲一列列,這些列可能隨時間而改變,從而中斷編譯後的代碼。發生這種情況時,SQL Server不會發出警告。

+3

儘管這是一個謹慎而好的建議,但它並沒有解決OP所面臨的直接問題。 – 2012-02-18 05:03:16