views:

20

answers:

1

I have a column with name and address data in a single column:

Jo Bloggs
Address Line 1
Address Line 2
PostCode

Is it possible to then create two computed columns based on this, and if so how? e.g.

RecipientName

Jo Bloggs

Address

Address Line 1
Address Line 2
PostCode

I'm using SQL Server 2005

A: 

You can do it like this;

CREATE TABLE ...
(
 ...
 WholeAddress  VARCHAR(256),
 RecipientName AS dbo.fnGetAddressPart(1, WholeAddress),
 Address       AS dbo.fnGetAddressPart(2, WholeAddress)
)

Where the UDF is along the lines of;

CREATE FUNCTION fnGetAddressPart (@PARTID TINYINT, @DATA VARCHAR(256)) RETURNS VARCHAR(256) AS BEGIN
    DECLARE @POS INT SET @POS = CHARINDEX(CHAR(13) + CHAR(10), @DATA, 1)
    IF (@POS = 0 OR LEN(@DATA) <= 2) --no new lines or just \r\n
        RETURN CASE @PARTID
            WHEN 1 THEN @DATA --return name only
            ELSE '' --no address part
        END

    RETURN CASE @PARTID
        WHEN 1 THEN LEFT(@DATA, @POS - 2)
        ELSE RIGHT(@DATA, LEN(@DATA) - @POS - 1)
    END
END

However it would be better to break out the address elements into individual fields.

Alex K.