IF NOT EXISTS (SELECT * FROM SYSCOLUMNS INNER JOIN SYSOBJECTS ON SYSOBJECTS.id = SYSCOLUMNS.id 
               WHERE SYSCOLUMNS.NAME = 'SUBEID' AND SYSOBJECTS.name = 'FTRYERI')
ALTER TABLE dbo.FTRYERI ADD
	SUBEID int NULL
GO

IF NOT EXISTS(select sysobjects.id from sysconstraints inner join sysobjects on sysobjects.id = constid where sysobjects.name = 'FK_FTRYERI_SUBELER' and xtype='F')
ALTER TABLE dbo.FTRYERI ADD CONSTRAINT
	FK_FTRYERI_SUBELER FOREIGN KEY
	(
	SUBEID
	) REFERENCES dbo.SUBELER
	(
	SUBEID
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 
	
GO

DECLARE 
  @ILKSUBEID int
  
SELECT TOP 1 @ILKSUBEID = SUBEID FROM HRANDEVUFTR   

IF @ILKSUBEID IS NULL
	SELECT TOP 1 @ILKSUBEID = SUBEID FROM SUBELER WHERE MEDISOFT = 1

-- PRINT STR(@ILKSUBEID)
  
UPDATE FTRYERI SET SUBEID = @ILKSUBEID
FROM FTRYERI WHERE SUBEID IS NULL 
GO

ALTER TABLE dbo.FTRYERI ALTER COLUMN
	SUBEID int NOT NULL
GO