IF NOT EXISTS (SELECT * FROM SYSCOLUMNS INNER JOIN SYSOBJECTS ON SYSOBJECTS.id = SYSCOLUMNS.id 
               WHERE SYSCOLUMNS.NAME = 'USERID' AND SYSOBJECTS.name = 'HASILAR')
ALTER TABLE dbo.HASILAR ADD
    USERID INT
GO   

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_HASILAR_USERID]') AND parent_object_id = OBJECT_ID(N'[dbo].[HASILAR]'))
ALTER TABLE [dbo].[HASILAR]  WITH CHECK ADD  CONSTRAINT [FK_HASILAR_USERID] FOREIGN KEY([USERID])
REFERENCES [dbo].[USER] ([USERID])
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_HASILAR_USERID]') AND parent_object_id = OBJECT_ID(N'[dbo].[HASILAR]'))
ALTER TABLE [dbo].[HASILAR] CHECK CONSTRAINT [FK_HASILAR_USERID]
GO

UPDATE    HASILAR
SET              USERID = [USER].USERID
FROM         HASILAR INNER JOIN
                      TSAGLIKP ON HASILAR.SPID = TSAGLIKP.SPID INNER JOIN
                      [USER] ON TSAGLIKP.TCKIMLIKNO = [USER].TCKIMLIKNO
WHERE     (HASILAR.KYTARIH < GETDATE())
GO

UPDATE    HASILAR
SET              USERID = [USER].USERID
FROM         HASILAR INNER JOIN
                      [USER] ON HASILAR.SPID = [USER].SAGLIKPID
WHERE     (HASILAR.USERID IS NULL) AND (HASILAR.KYTARIH < GETDATE())
GO

