I'm new to tSQL functions and I'm trying to do the following:
I have a table like this called Projects:
+----------+--------------+
| Code | Previous_Code|
+----------+--------------+
| 001 | NULL |
| 002 | 001 |
| 003 | 002 |
| 004 | NULL |
| 005 | NULL |
+----------+--------------+
And I'd like to create an SQL function to produce the following query result:
+----------+--------------+
| Code | Original_Code|
+----------+--------------+
| 001 | 001 |
| 002 | 001 |
| 003 | 001 |
| 004 | 004 |
| 005 | 005 |
+----------+--------------+
I've come up with the function below:
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;
But it just seems to be in an infinite loop when it is run. Doe anyone one have any ideas or a better way of achieving the same result? Thanks in advance.
Previous_Codevalues until you reach aCodewith aPrevious_CodeofNULL, is that right? So,003 -> 002 -> 001 -> NULL, therefore "003" has anOriginal_Codeof "001". I'm not clear though why "001" has anOriginal_Codeof "001", when "004" and "005" both haveOriginal_Codes of "NULL"WHILEloop into one is a double disaster. What is your actual goal here? You would be far far better off using an inline table-value function.