2

我使用下面的查询,但说Incorrect syntax near if如何解决这个问题?

CREATE FUNCTION getCustomerAllReseller
(
    @code BIGINT 
)
RETURNS TABLE AS
RETURN (
    WITH Directories AS 
    (
        IF (@code < 0)
            SELECT code FROM CustomerAll WHERE code = @code
        ELSE
            SELECT code FROM Customer WHERE code = @code
    )
    SELECT * FROM Directories
)
4

3 回答 3

1

for 的语法with需要查询,而不是语句。您可以在带有联合的查询中使用条件:

WITH Directories AS (
  select code from CustomerAll where @code<0 and code=@code
  union all
  Select code from Customer where @code>=0 and code=@code
)
SELECT * FROM Directories
于 2013-09-05T05:42:58.400 回答
0

你不能使用IF,你必须SELECT使用CTE_definition_part

指定其结果集填充公用表表达式的 SELECT 语句。CTE_query_definition 的 SELECT 语句必须满足与创建视图相同的要求,但 CTE 不能定义另一个 CTE。有关详细信息,请参阅备注部分和 CREATE VIEW (Transact-SQL)。

http://technet.microsoft.com/en-us/library/ms175972.aspx

于 2013-09-05T05:39:56.340 回答
0

试试这个——

CREATE FUNCTION dbo.getCustomerAllReseller
(
    @code BIGINT
)
RETURNS TABLE AS
RETURN
(
    SELECT code 
    FROM dbo.CustomerAll 
    WHERE code = @code
        AND @code < 0

    UNION ALL

    SELECT code 
    FROM dbo.Customer 
    WHERE code = @code
        AND @code >= 0
)
于 2013-09-05T05:42:51.457 回答