I'm trying to update a table, specifically the phone numbers.
I have made two procedures (also converted both to functions):
CreateRandomMobileNumber
ALTER procedure [dbo].[GetRandomMobileNumber]( @min AS BIGINT, @max AS BIGINT, @mobile_num AS VARCHAR(20) ) AS BEGIN SELECT @min = 1, @max = 99999999 SELECT @mobile_num = CAST(CAST(((@max + 1) - @min) * Rand() + @min as bigint) as varchar(15)) SELECT @mobile_num = '04' + ' ' + SUBSTRING(@mobile_num, 1, 4) + ' ' + RIGHT(@mobile_num,4) SELECT @mobile_num END
CreateRandomPhoneNumber
ALTER procedure [dbo].[GetRandomPhoneNumber]( @min AS BIGINT, @max AS BIGINT, @phone_num AS VARCHAR(20) ) AS BEGIN SELECT @min = 1, @max = 99999999 Select @phone_num = CAST(CAST(((@max + 1) - @min) * Rand() + @min as bigint) as varchar(15)) SELECT @phone_num = CASE WHEN LEFT(@phone_num, 1) BETWEEN 1 AND 6 THEN '02' + ' ' + SUBSTRING(@phone_num, 1, 4) + ' ' + RIGHT(@phone_num,4) WHEN LEFT(@phone_num, 1) BETWEEN 7 AND 8 THEN '03' + ' ' + SUBSTRING(@phone_num, 1, 4) + ' ' + RIGHT(@phone_num,4) ELSE '07' + ' ' + SUBSTRING(@phone_num, 1, 4) + ' ' + RIGHT(@phone_num,4) END SELECT @phone_num END
What I want to do is be able to call these on an update, this is the insert statement:
; WITH CTE AS
(
SELECT *, rn = ROW_NUMBER() OVER ( ORDER BY newid() )
FROM anon_PersonChangeData
)
UPDATE c1
SET c1.personNewGender = c2.personCurrentGender
, c1.personNewFirstName = c2.personCurrentFirstName
, c1.personNewSurname = c3.personCurrentSurname
, c1.personNewHomeEmail = CASE
WHEN c1.personStatus IN ('both', 'candidate') AND c1.personCurrentFirstName LIKE '%p%'
THEN c2.personCurrentFirstName + '.' + c3.personCurrentSurname + '@yoohoo.com'
WHEN c1.personStatus IN ('both', 'candidate') AND c1.personCurrentFirstName LIKE '%e%'
THEN c2.personCurrentFirstName + '.' + c3.personCurrentSurname + '@hatmail.com'
ELSE c2.personCurrentFirstName + '.' + c3.personCurrentSurname + '@gmoil.com'
END
, c1.personNewWorkEmail = NULL
, c1.personNewHomePhone = dbo.GetRandomPhoneNumber
, c1.personNewWorkPhone = NULL
, c1.personNewMobilePhone = dbo.GetRandomMobileNumber
FROM CTE c1
INNER JOIN CTE c2 ON c1.rn = c2.rn
INNER JOIN CTE c3 ON c2.rn = c3.rn
I have tried a few different things and my function versions keep giving me the following error:
Invalid use of a side-effecting operator 'rand' within a function.
Any help would be much appreciated.