如果其他功能

时间:2013-09-05 05:33:53

标签: sql sql-server tsql

我使用下面的查询但是说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
)

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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

答案 2 :(得分: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
)