USE [HRISDEV]
GO

--INSERT INTO [dbo].[masking]
--           ([NIP]
--           ,[nama_sebelum]
--           ,[nama_sesudah])
--SELECT
--	NIP,
--	NM_PEG,
--	NULL
--FROM
--	SPG_DATA_CURRENT
--GO


--SELECT * FROM masking
---------------
DECLARE 
	@nip VARCHAR(32),
	@nama VARCHAR(200)

DECLARE list_cursor CURSOR FOR  
SELECT NIP, nama_sebelum
FROM masking 

OPEN list_cursor  
FETCH NEXT FROM list_cursor INTO @nip, @nama

WHILE @@FETCH_STATUS = 0  
BEGIN  

	DECLARE 
		@jml_kata TINYINT = 0,
		@n_kata TINYINT = 1,
		@hasil VARCHAR(200) = '',
		@kelamin char(1)

	SELECT @kelamin = JNS_KELAMIN_PEG FROM SPG_DATA_CURRENT WHERE NIP = @nip

	SELECT @jml_kata = FLOOR(RAND() * 3) + 1

	WHILE ( @n_kata <= @jml_kata)
		BEGIN
			
			IF (@kelamin = '1')
				BEGIN
					IF (@n_kata = 1)	-- first name
						SELECT TOP 1 @hasil = @hasil + nama FROM template_nama WHERE depan = 1 AND pria = 1 ORDER BY NEWID()
					ELSE IF (@n_kata = @jml_kata AND @jml_kata <> 1)	-- last name
						SELECT TOP 1 @hasil = @hasil + nama FROM template_nama WHERE belakang = 1 AND pria = 1 ORDER BY NEWID()
					ELSE
						SELECT TOP 1 @hasil = @hasil + nama FROM template_nama WHERE pria = 1 ORDER BY NEWID()
				END
			ELSE
				BEGIN
					IF (@n_kata = 1)	-- first name
						SELECT TOP 1 @hasil = @hasil + nama FROM template_nama WHERE depan = 1 AND wanita = 1 ORDER BY NEWID()
					ELSE IF (@n_kata = @jml_kata AND @jml_kata <> 1)	-- last name
						SELECT TOP 1 @hasil = @hasil + nama FROM template_nama WHERE belakang = 1 AND wanita = 1 ORDER BY NEWID()
					ELSE
						SELECT TOP 1 @hasil = @hasil + nama FROM template_nama WHERE wanita = 1 ORDER BY NEWID()
				END

			SET @n_kata  = @n_kata  + 1
			SET @hasil = @hasil + ' '
		END
	--SELECT UPPER(@hasil)

	UPDATE masking SET nama_sesudah = UPPER(@hasil) WHERE NIP = @nip AND nama_sebelum = @nama

	FETCH NEXT FROM list_cursor INTO @nip, @nama  
END  

CLOSE list_cursor  
DEALLOCATE list_cursor 


