SQL函数遍历表

时间:2018-08-21 09:08:16

标签: sql sql-server function loops tsql

我是tSQL函数的新手,我正在尝试执行以下操作:

我有一个这样的表,叫做Projects:

+----------+--------------+
| Code     | Previous_Code|
+----------+--------------+
| 001      | NULL         |
| 002      | 001          |
| 003      | 002          |
| 004      | NULL         |
| 005      | NULL         |
+----------+--------------+

我想创建一个SQL函数以产生以下查询结果:

+----------+--------------+
| Code     | Original_Code|
+----------+--------------+
| 001      | 001          |
| 002      | 001          |
| 003      | 001          |
| 004      | 004          |
| 005      | 005          |
+----------+--------------+

我想出了以下功能:

CREATE FUNCTION OriginalProjectCode (@Code VARCHAR(3))
RETURNS VARCHAR(3)
AS
BEGIN
DECLARE @Code2 AS VARCHAR(3);
WHILE @Code IS NOT NULL
    BEGIN
        SET @Code2 = @Code;
        SET @Code = ('SELECT [Previous_Code] FROM 
        Projects WHERE [Code] = ' + @Code);
        SET @Code2 = @Code;
    END;
RETURN @Code2;
END;

但是它似乎在运行时处于无限循环中。有人对实现相同结果有任何想法或更好的方法吗?提前致谢。

2 个答案:

答案 0 :(得分:1)

看来 { "development": { "username": "postgres", "password": "postgres", "database": "database_development", "host": "127.0.0.1", "dialect": "mysql" }, "test": { "username": "root", "password": null, "database": "database_test", "host": "127.0.0.1", "dialect": "mysql" }, "production": { "username": "root", "password": null, "database": "database_production", "host": "127.0.0.1", "dialect": "mysql" } } 表达式很简单:

case

答案 1 :(得分:0)

希望这会有所帮助!

    CREATE TABLE #Projects(Code VARCHAR(10),Previous_Code VARCHAR(10))

    INSERT INTO #Projects
    SELECT '001',NULL  Union ALL
    SELECT '002','001' Union ALL
    SELECT '003','002' Union ALL
    SELECT '004',NULL  Union ALL
    SELECT '005',NULL 

    DECLARE @id varchar(10)='003'

    ;with cte
    AS
    (
         select code,code as Original_Code,ISNULL(Previous_Code,code)Previous_Code
           from #Projects
           union all
          select c.Code,p.code as Original_Code, p.Previous_Code
           from #Projects p
             join cte c on c.Previous_Code = p.code  

    )

    SELECT code,Original_Code
    from cte 
    WHERE
        1= ( CASE WHEN Previous_Code IS NULL AND code !=Original_Code then 1
            WHEN code=Original_Code and Original_Code=Previous_Code then 1
            ELSE 0 END)
    order by code,Previous_Code


    DROP TABLE #Projects