-- clear tables from previous runs of this script
BEGIN TRY DROP TABLE dbo.tblPhoneType DROP TABLE dbo.tblPhone END TRY BEGIN CATCH END CATCH

-- create tables
CREATE TABLE dbo.tblPhoneType ( 
	codPhoneType TINYINT, 
	PhoneType VARCHAR(50),
	PRIMARY KEY (codPhoneType))
GO

CREATE TABLE dbo.tblPhone ( 
	codUser INT, 
	codPhoneType TINYINT, 
	PhoneNumber VARCHAR(20), 
	ListThisNumber TINYINT,
	PRIMARY KEY (codUser, codPhoneType))
GO

-- populate tblPhoneType
INSERT INTO dbo.tblPhoneType VALUES ( 1, 'Residential')
GO
INSERT INTO dbo.tblPhoneType VALUES ( 2, 'Business')
GO
INSERT INTO dbo.tblPhoneType VALUES ( 3, 'Mobile')
GO
INSERT INTO dbo.tblPhoneType VALUES ( 4, 'Fax')
GO 

-- populate tblPhone
INSERT INTO dbo.tblPhone VALUES ( 1, 1, '1 281 444 5555' , 1 )
GO
INSERT INTO dbo.tblPhone VALUES ( 1, 2, '55 11 4582 2752', 1)
GO
INSERT INTO dbo.tblPhone VALUES ( 1, 3, '1 471 333 1234', 0)
GO
INSERT INTO dbo.tblPhone VALUES ( 2, 1, '1 XXX XXX XXXXX', 1)
GO


-- declare and set varuables
DECLARE @AllPhones VARCHAR(1000)
DECLARE @PhoneNumber VARCHAR(20)
DECLARE @ListThisNumber TINYINT

SET @AllPhones = ''

-- declare cursor
DECLARE curPersonalPhones CURSOR FAST_FORWARD FOR 
	SELECT PhoneNumber , ListThisNumber 
	FROM dbo.tblPhone WHERE codUser = 1

-- open cursor
OPEN curPersonalPhones 
-- fetch first set of values
FETCH NEXT 
	FROM curPersonalPhones 
	INTO @PhoneNumber, @ListThisNumber 

-- loop while FETCH_STATUS is OK
WHILE @@FETCH_STATUS = 0  
	BEGIN 
		-- do whatever is required
		IF @ListThisNumber = 0  
			SET @PhoneNumber = '***********'
		SET @AllPhones = @AllPhones + @PhoneNumber + ' & ' 
		-- fetch next set of values
		FETCH NEXT 
			FROM curPersonalPhones  
			INTO @PhoneNumber, @ListThisNumber 
	END

-- close and deallocate the cursor
CLOSE curPersonalPhones 
DEALLOCATE curPersonalPhones

SELECT @AllPhones
GO