
declare @TelehealthUserDetails table (
	Id int IDENTITY(1,1) NOT NULL,
	UserId int NOT NULL,
	ReminderSendTextMessage bit NOT NULL,
	ReminderSendVoiceCommand bit NOT NULL,
	PrimaryCarePhysician nvarchar(100) NULL,
	CurrentWeight nvarchar(1000) NULL,
	Height nvarchar(1000) NULL,
	CreatedUtc datetime NOT NULL
	)

insert into @TelehealthUserDetails (UserId, ReminderSendTextMessage, ReminderSendVoiceCommand, PrimaryCarePhysician, CurrentWeight, Height, CreatedUtc)
select u.cmsuserid,0,0,pcp.value,bw.value,bh.value,GETUTCDATE()
from UserSettings u
	join CmsUserTbl cm on cm.CmsUserId=u.cmsuserid and cm.SecurityLevelId=3
	left outer join UserSettings pcp on pcp.cmsuserid =u.cmsuserid and pcp.settingtypeid=(select id from UserSettingsTypes where rowid='690F0D29-A393-41AB-AD1C-AD06F396EDC3')
	left outer join UserSettings bw on bw.cmsuserid =u.cmsuserid and bw.settingtypeid=(select id from UserSettingsTypes where rowid='690F0D29-A393-41AB-AD1C-AD06F396EDC1')
	left outer join UserSettings bh on bh.cmsuserid =u.cmsuserid and bh.settingtypeid=(select id from UserSettingsTypes where rowid='690F0D29-A393-41AB-AD1C-AD06F396EDC2')
where u.value='True' and u.settingtypeid=1


MERGE INTO dbo.TelehealthUserDetails AS TARGET  
USING @TelehealthUserDetails AS SOURCE  
ON TARGET.userid = SOURCE.userid
WHEN NOT MATCHED BY TARGET THEN
INSERT (UserId, ReminderSendTextMessage, ReminderSendVoiceCommand, PrimaryCarePhysician, CurrentWeight, Height, CreatedUtc)
VALUES (SOURCE.UserId, SOURCE.ReminderSendTextMessage, SOURCE.ReminderSendVoiceCommand, SOURCE.PrimaryCarePhysician, SOURCE.CurrentWeight, SOURCE.Height, SOURCE.CreatedUtc);
