-- 1399/01/26
-- Script after 1395/10/01
-- Select DataBase To Use
-- chanage database
USE [Darmangah]

Go

CREATE TABLE [dbo].[morajeat_filter](
	[code_user] [int] NOT NULL,
	[tarikh_from] [char](10) NOT NULL,
	[tarikh_to] [char](10) NOT NULL,
 CONSTRAINT [PK_morajeat_filter] PRIMARY KEY CLUSTERED 
(
	[code_user] ASC
) ON [PRIMARY]
)

GO

insert morajeat_filter (code_user,tarikh_from,tarikh_to) values (1,'1398/01/01','1398/01/01')

Go

--1395/10/10

ALTER TABLE [dbo].[EasyDent4]
   ADD  [Auto_Tarnsfer_Second] [int] NULL  

GO

update  EasyDent4 set Auto_Tarnsfer_Second=5 where Auto_Tarnsfer_Second is NULL

GO

ALTER TABLE [dbo].[bimaran]
   ADD  [transferred] [bit] NULL  

GO

ALTER TABLE [dbo].[bimaran_image]
   ADD  [selected] [bit] NULL  

GO


ALTER TABLE [dbo].[users]
   add [ab_edit_r_bimar] [bit] NULL 

Go


ALTER TABLE [dbo].[users]
   add [ab_edit_r_bimeh] [bit] NULL 

Go

ALTER TABLE [dbo].[users]
   add [active] [bit] NULL 

Go

ALTER TABLE [dbo].[Tarikh]
   add [mamoriat] [int] NULL 

Go

ALTER TABLE [dbo].[Tarikh]
   add [morakhasi] [int] NULL 

Go

ALTER TABLE [dbo].[Tarikh]
   add [time_mamoriat] [char] (5) NULL 

Go

ALTER TABLE [dbo].[Tarikh]
   add [time_morakhasi] [char] (5) NULL 

Go

ALTER TABLE [dbo].[Tarikh]
   add [description] [nvarchar] (200) NULL 

Go

ALTER TABLE [dbo].[Moshtari]
   add [saat_vord_5] [char] (5) NULL 

Go

ALTER TABLE [dbo].[Moshtari]
   add [saat_khoroj_5] [char] (5) NULL 

Go
ALTER TABLE [dbo].[bimaran] ALTER COLUMN  [shsh] [varchar] (50)  NULL 
Go

ALTER TABLE [dbo].[users]
   add [ab_edit_code_bimar_paziresh] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_edit_code_pezeshk_paziresh] [bit] NULL 
Go
update users set active=1 where active is null
Go
-- 1395/11/14

ALTER TABLE [dbo].[noskhehha]
   add [r_mokammel] [money] NULL 
Go
ALTER TABLE [dbo].[noskhehha]
   add [r_yaraneh] [money] NULL 
Go
ALTER TABLE [dbo].[noskhehha]
   add [r_pezeshk] [money] NULL 
Go

-- 1395/11/16

Go

CREATE TABLE [dbo].[noskhehha_filter](
	[code_user] [int] NOT NULL,
	[tarikh_from] [char](10) NOT NULL,
	[tarikh_to] [char](10) NOT NULL,
 CONSTRAINT [PK_noskhehha_filter] PRIMARY KEY CLUSTERED 
(
	[code_user] ASC
) ON [PRIMARY]
)

GO

insert noskhehha_filter (code_user,tarikh_from,tarikh_to) values (1,'90/01/01','99/01/01')

Go
-- 1395/11/18

ALTER TABLE [dbo].[noskhehha_filter]
   add [code_pezeshk] [int] NULL 

GO

-- 1395/11/20

ALTER TABLE [dbo].[noskhehha_filter]
     ADD  [darsad] [float] NULL 
GO

ALTER TABLE [dbo].[morajeat]
    ALTER COLUMN[tozihat] [nvarchar](1000)  NULL 
    
 Go

-- Run for old exe     :)
-- ALTER TABLE [dbo].[morajeat]
 --   ALTER COLUMN[tozihat] [ntext] NULL 

-- 1395/12/01

CREATE TABLE [dbo].[tarikh_shift](
	[tarikh] [char](10) NOT NULL,
	[sh1] [int] NULL,
	[sh2] [int] NULL,
	[sh3] [int] NULL,
	[sh4] [int] NULL,
 CONSTRAINT [PK_tarikh_shift] PRIMARY KEY CLUSTERED 
(
	[tarikh] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO

-- 1395/12/06

CREATE TABLE [dbo].[sopro](
	[id] [int] NOT NULL,
	[active] [bit] NULL,
	[Image_Path] [nvarchar](500) NULL,
	[Count_Taransfer] [int] NULL,
	[Auto_Tarnsfer_Second] [int] NULL,
 CONSTRAINT [PK_sopro] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO

insert sopro (id,active,Image_Path,Count_Taransfer,Auto_Tarnsfer_Second) values (1,0,'',10,10)

Go

-- update bimaran set transferred=null


Go
UPDATE   darmanha  SET  r_azad = 0 WHERE (r_azad IS NULL) or (RTRIM(LTRIM(cast(r_azad as char)))='')
Go
UPDATE   darmanha  SET  r_bimeh = 0 WHERE (r_bimeh IS NULL) or (RTRIM(LTRIM(cast(r_bimeh as char)))='')
Go
UPDATE   darmanha  SET  r_bimar = 0 WHERE (r_bimar IS NULL) or (RTRIM(LTRIM(cast(r_bimar as char)))='')
Go
UPDATE   darmanha  SET  r_mabeh = 0 WHERE (r_mabeh IS NULL) or (RTRIM(LTRIM(cast(r_mabeh as char)))='')
Go
UPDATE   darmanha  SET  r_takhfif = 0 WHERE (r_takhfif IS NULL) or (RTRIM(LTRIM(cast(r_takhfif as char)))='')
Go
UPDATE   darmanha  SET  r_pezeshk = 0 WHERE (r_pezeshk IS NULL) or (RTRIM(LTRIM(cast(r_pezeshk as char)))='')
Go
UPDATE   darmanha  SET  r_mokammel = 0 WHERE (r_mokammel IS NULL) or (RTRIM(LTRIM(cast(r_mokammel as char)))='')
Go
UPDATE   darmanha  SET  r_yaraneh = 0 WHERE (r_yaraneh IS NULL) or (RTRIM(LTRIM(cast(r_yaraneh as char)))='')
Go
UPDATE   darmanha  SET  r_bed = 0 WHERE (r_bed IS NULL) or (RTRIM(LTRIM(cast(r_bed as char)))='')
Go
UPDATE   darmanha  SET  radif = 0 WHERE (radif IS NULL) or (RTRIM(LTRIM(cast (radif as char)))='')
Go
UPDATE   darmanha  SET  code_noa_khedmat = 22 WHERE (code_noa_khedmat IS NULL) or (RTRIM(LTRIM(cast (code_noa_khedmat as char)))='')
Go
UPDATE   darmanha  SET  code_ertebat = 1 WHERE (code_ertebat IS NULL) or (RTRIM(LTRIM(cast (code_ertebat as char)))='')
Go
UPDATE   darmanha  SET  code_ertebat = 1 WHERE (len(code_ertebat)=0) or (RTRIM(LTRIM(cast (code_ertebat as char)))='')
Go
UPDATE   darmanha  SET  zarib_k = 0 WHERE (zarib_k IS NULL) or (RTRIM(LTRIM(cast (zarib_k as char)))='')
Go
UPDATE   darmanha  SET  zarib_k_labratvar = 0 WHERE (zarib_k_labratvar IS NULL) or (RTRIM(LTRIM(cast (zarib_k_labratvar as char)))='')
Go
UPDATE   darmanha  SET  zarib_k_masraf = 0 WHERE (zarib_k_masraf IS NULL) or (RTRIM(LTRIM(cast (zarib_k_masraf as char)))='')
Go
UPDATE   darmanha  SET  code_daro = 1 WHERE (code_daro IS NULL) or (RTRIM(LTRIM(cast (code_daro as char)))='')
Go
UPDATE   darmanha  SET  meghdar = 0 WHERE (meghdar IS NULL) or (RTRIM(LTRIM(cast (meghdar as char)))='')
Go
UPDATE   darmanha  SET  r_bed=r_azad-r_bimeh+r_mabeh-r_takhfif-r_yaraneh-r_mokammel
Go
UPDATE   darmanha  SET  r_a = 0 WHERE (r_a IS NULL) or (RTRIM(LTRIM(cast (r_a as char)))='')
Go
UPDATE   darmanha  SET  r_d = 0 WHERE (r_d IS NULL) or (RTRIM(LTRIM (cast(r_d as char)))='')
Go


UPDATE   morajeat  SET  r_azad = 0 WHERE (r_azad IS NULL) or (RTRIM(LTRIM(cast (r_azad as char)))='')
Go
UPDATE   morajeat  SET  r_bimeh = 0 WHERE (r_bimeh IS NULL) or (RTRIM(LTRIM(cast (r_bimeh as char)))='')
Go
UPDATE   morajeat  SET  r_bimar = 0 WHERE (r_bimar IS NULL) or (RTRIM(LTRIM(cast (r_bimar as char)))='')
Go
UPDATE   morajeat  SET  r_mabeh = 0 WHERE (r_mabeh IS NULL) or (RTRIM(LTRIM(cast (r_mabeh as char)))='')
Go
UPDATE   morajeat  SET  r_takhfif = 0 WHERE (r_takhfif IS NULL) or (RTRIM(LTRIM(cast (r_takhfif as char)))='')
Go
UPDATE   morajeat  SET  r_takhfif_p = 0 WHERE (r_takhfif_p IS NULL) or (RTRIM(LTRIM(cast (r_takhfif_p as char)))='')
Go
UPDATE   morajeat  SET  r_labratvar_2 = 0 WHERE (r_labratvar_2 IS NULL) or (RTRIM(LTRIM(cast (r_labratvar_2 as char)))='')
Go
UPDATE   morajeat  SET  r_pezeshk = 0 WHERE (r_pezeshk IS NULL) or (RTRIM(LTRIM(cast (r_pezeshk as char)))='')
Go
UPDATE   morajeat  SET  r_mokammel = 0 WHERE (r_mokammel IS NULL) or (RTRIM(LTRIM(cast (r_mokammel as char)))='')
Go
UPDATE   morajeat  SET  r_yaraneh = 0 WHERE (r_yaraneh IS NULL) or (RTRIM(LTRIM(cast (r_yaraneh as char)))='')
Go
UPDATE   morajeat  SET  r_bed = 0 WHERE (r_bed IS NULL) or (RTRIM(LTRIM(cast (r_bed as char)))='')
Go
UPDATE   morajeat  SET  r_bes = 0 WHERE (r_bes IS NULL) or (RTRIM(LTRIM(cast (r_bes as char)))='')
Go
UPDATE   morajeat  SET  radif = 0 WHERE (radif IS NULL) or (RTRIM(LTRIM(cast (radif as char)))='')
Go
UPDATE   morajeat  SET  code_noa_khedmat = 22 WHERE (code_noa_khedmat IS NULL) or (RTRIM(LTRIM(cast (code_noa_khedmat as char)))='')
Go
UPDATE   morajeat  SET  code_ertebat = 1 WHERE (code_ertebat IS NULL) or (RTRIM(LTRIM(cast (code_ertebat as char)))='')
Go
UPDATE   morajeat  SET  code_ertebat = 1 WHERE (len(code_ertebat)=0) or (RTRIM(LTRIM(cast (code_ertebat as char)))='')
Go
UPDATE   morajeat  SET  zarib_k = 0 WHERE (zarib_k IS NULL) or (RTRIM(LTRIM(cast (zarib_k as char)))='')
Go
UPDATE   morajeat  SET  code_daro = 1 WHERE (code_daro IS NULL) or (RTRIM(LTRIM(cast (code_daro as char)))='')
Go
UPDATE   morajeat  SET  r_mandeh = 1 WHERE ( r_mandeh IS NULL) or (RTRIM(LTRIM(cast (r_mandeh as char)))='')
Go
UPDATE   morajeat  SET  code_bakhsh = 0 WHERE ( code_bakhsh IS NULL) or (RTRIM(LTRIM(cast (code_bakhsh as char)))='')
Go
UPDATE   morajeat  SET  code_pezeshk = 0 WHERE ( code_pezeshk IS NULL) or (RTRIM(LTRIM(cast (code_pezeshk as char)))='')
Go
UPDATE   morajeat  SET  code_bimeh = 0 WHERE ( code_bimeh IS NULL) or (RTRIM(LTRIM(cast (code_bimeh as char)))='')
Go
UPDATE   morajeat  SET  code_darman = 0 WHERE ( code_darman IS NULL) or (RTRIM(LTRIM(cast (code_darman as char)))='')
Go
UPDATE   morajeat  SET  tedad_darman = 1 WHERE ( tedad_darman IS NULL) or (RTRIM(LTRIM(cast (tedad_darman as char)))='')
Go
UPDATE   morajeat  SET  code_pay = 1 WHERE ( code_pay IS NULL) or (RTRIM(LTRIM(cast (code_pay as char)))='')
Go
UPDATE   morajeat  SET  code_dastyar = 0 WHERE ( code_dastyar IS NULL) or (RTRIM(LTRIM(cast (code_dastyar as char)))='')
Go
UPDATE   morajeat  SET  code_yaraneh = 0 WHERE ( code_yaraneh IS NULL) or (RTRIM(LTRIM(cast (code_yaraneh as char)))='')
Go
UPDATE   morajeat  SET  code_mokammel = 0 WHERE ( code_mokammel IS NULL) or (RTRIM(LTRIM(cast (code_mokammel as char)))='')
Go
UPDATE  morajeat  SET  r_bed=r_azad-r_bimeh+r_mabeh-r_takhfif-r_yaraneh-r_mokammel-r_takhfif_p
Go

-- 1395/12/15

update users set mohasebe_mandeh_dar_khat_paziresh=0

Go

-- 1395/12/16

ALTER TABLE [dbo].[users]
   add [code_shobeh] [int] NULL 

Go

CREATE TABLE [dbo].[shobeh](
	[code_shobeh] [int] NOT NULL,
	[name_shobeh] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_shobeh] PRIMARY KEY CLUSTERED 
(
	[code_shobeh] ASC
) ON [PRIMARY]
) ON [PRIMARY]

GO
insert shobeh (code_shobeh,name_shobeh)values (1,'shobeh 1')
Go
insert shobeh (code_shobeh,name_shobeh)values (2,'shobeh 2')
Go
insert shobeh (code_shobeh,name_shobeh)values (3,'shobeh 3')
Go

ALTER TABLE [dbo].[morajeat]
   add [code_shobeh] [int] NULL 
Go
ALTER TABLE [dbo].[noskhehha]
   add [code_shobeh] [int] NULL 
Go
ALTER TABLE [dbo].[vaght_dehi]
   add [code_shobeh] [int] NULL 
Go
ALTER TABLE [dbo].[bimaran]
   add [code_shobeh] [int] NULL 
Go
 -- 1396/01/16
ALTER TABLE [dbo].[bakhshha]
   add [orderw] [int] NULL 

Go
--1396/01/20
Go
ALTER TABLE [dbo].[morajeat]
   add [r_bimeh_tas] [bit] NULL 

Go
update morajeat set r_bimeh_tas=0 where r_bimeh_tas is null
Go

ALTER TABLE [dbo].[morajeat]
   add [r_bed_tas] [bit] NULL 

Go
update morajeat set r_bed_tas=0 where r_bed_tas is null
Go
ALTER TABLE [dbo].[users]
   add [ab_r_bed_tas] [bit] NULL 
Go
update users set ab_r_bed_tas=0 where ab_r_bed_tas is null
Go
ALTER TABLE [dbo].[users]
   add [ab_r_bimeh_tas] [bit] NULL 
Go
update users set ab_r_bimeh_tas=0 where ab_r_bimeh_tas is null
Go
ALTER TABLE [dbo].[settinga]
  add [code_bakhsh_sandogh] [int] NULL
Go
update settinga set code_bakhsh_sandogh=0 where code_bakhsh_sandogh is null
Go
ALTER TABLE [dbo].[bimaran]
  add [tarikh_paziresh] char(10) NULL
Go
ALTER TABLE [dbo].[morajeat]
  add [cm_linke_sandogh] int NULL
Go


--1396/02/02

Go
ALTER TABLE [dbo].[settinga]
  add [auto_code_morajeh] [bit] NULL
Go
ALTER TABLE [dbo].[settinga]
  add [auto_code_noskheh] [bit] NULL
Go
update settinga set auto_code_morajeh=0 where auto_code_morajeh is null
Go
update settinga set auto_code_noskheh=0 where auto_code_noskheh is null
Go
Update morajeat set cm_linke_sandogh=0 where cm_linke_sandogh is null

Go
--1396/02/04
Go
ALTER TABLE [dbo].[reminder]
  add [next_call] char(10) NULL
Go
ALTER TABLE [dbo].[reminder]
  add [code_result] int NULL
Go
GO
CREATE TABLE [dbo].[result_follow_up](
	[code_result] [int] NOT NULL,
	[name_result] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_result_follow_up] PRIMARY KEY CLUSTERED 
(
	[code_result] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
insert result_follow_up (code_result,name_result) values (1,N'بدون نتیجه')
GO
insert result_follow_up (code_result,name_result) values (2,N'نتیجه خوب')
GO
ALTER TABLE [dbo].[settinga]
  add [text_alarm_reminder] [nvarchar](250) NULL
Go
update settinga set text_alarm_reminder=N'   یاد اوری  جهت پیگیری      '
GO
CREATE TABLE [dbo].[Fingers](
	[SN] [int] IDENTITY(1,1) NOT NULL,
	[Finger] [image] NOT NULL,
	[code_person] [int] NOT NULL,
 CONSTRAINT [PK_Fingers] PRIMARY KEY CLUSTERED 
(
	[SN] ASC
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

CREATE TABLE [dbo].[Fingers_bmp](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[finger_bmp] [image] NOT NULL,
	[code_person] [int] NOT NULL,
	[insert_time] [datetime] NOT NULL,
	[tarikh] [char](10) NOT NULL,
	[code_user_insert] [int] NULL,
	[code_user_edit] [int] NULL,
	[selected] [bit] NULL,
 CONSTRAINT [PK_Fingers_bmp] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

-- 1396/02/26

-- SELECT name FROM sysobjects  WHERE type = 'TR'

ALTER TABLE [dbo].[settinga]
  add [len_sh_bimeh_bimaran] [int] NULL
Go
update settinga set len_sh_bimeh_bimaran=16 where len_sh_bimeh_bimaran is null
Go

-- 1396/02/30

ALTER TABLE [dbo].[settinga]
  add [Show_Tooth_Number_EN] [bit] NULL
Go
update settinga set Show_Tooth_Number_EN=0 where Show_Tooth_Number_EN is null
Go
-- update settinga set Show_Tooth_Number_EN=1
Go

-- 1396/03/02

ALTER TABLE [dbo].[users]
   add [ab_export_access] [bit] NULL 

Go
update users set ab_export_access=0 where ab_export_access is null
Go
-- 1396/02/06
Go
ALTER TABLE [dbo].[settinga]
  add [Show_List_bedehi_sandogh] [bit] NULL
Go
Update settinga set Show_List_bedehi_sandogh=1 where Show_List_bedehi_sandogh is null
Go

-- 1396/02/08

Go
ALTER TABLE [dbo].[moaref]
    ADD [darsad] float NULL
Go
update moaref set darsad=0 where darsad is null
Go

-- 1396/03/10
Go
update setting set Certificate_Pass='NeedSoft@1392$' 
Go
ALTER TABLE [dbo].[bimaran]
   ADD  [elat_asli_morajeh] [nvarchar](200) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [alaem_hamrah] [nvarchar](200) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [sabeghe_famili] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_daei] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_amo] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_madar] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_pedar] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_pedar_bozorg_madari] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_pedar_bozorg_pedari] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_baradaran] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_khaharan] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [f_ghireh] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [eghdamat_darmani_ghabli] [nvarchar](200) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [sabegheh_bimari] [nvarchar](200) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [sabegheh_masraf_daro] [nvarchar](200) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [masraf_alkol] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_masraf_alkol] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [t_m_masraf_alkol] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [masraf_sigar] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_masraf_sigar] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [noa_sigar] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [masraf_ghelyan] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_masraf_ghelyan] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [masraf_moharek] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_masraf_moharek] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [masraf_badansazi] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_masraf_badansazi] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [varzesh] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_varzesh] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [hasasiat_daroei] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_hasasiat_daroei] [nvarchar](20) NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [bihesi] [bit] NULL
GO
ALTER TABLE [dbo].[bimaran]
   ADD  [m_bihesi] [nvarchar](20) NULL
GO

-- 1396/04/12

GO
CREATE TABLE [dbo].[noa_kala](
	[code_noa_kala] [int] NOT NULL,
	[name_noa_kala] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_noa_kala] PRIMARY KEY CLUSTERED 
(
	[code_noa_kala] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[kala]
   ADD [selected] [bit] NULL 
Go

ALTER TABLE [dbo].[kala]
   ADD [code_noa_kala] [int] NULL 
Go

ALTER TABLE [dbo].[anbar_Itm]
   ADD [code_noa_kala] [int] NULL 
Go

ALTER TABLE [dbo].[kala]
   ADD [Anbar_Itm_Copy_Past] [int] NULL 
Go
insert noa_kala (code_noa_kala,name_noa_kala) values (0,N'انتخاب نوع کالا')
Go
insert noa_kala (code_noa_kala,name_noa_kala) values (1,N'اموالی')
GO
insert noa_kala (code_noa_kala,name_noa_kala) values (2,N'مصرفی')
GO
insert noa_kala (code_noa_kala,name_noa_kala) values (3,N'نمونه')
GO

-- 1396/04/14

Go
ALTER TABLE [dbo].[bimaran]
   add [web_username][nvarchar](50) NULL
Go
ALTER TABLE [dbo].[bimaran]
   add [web_password][nvarchar](50) NULL
Go
update bimaran set web_username=code_meli where web_username is null
Go
update bimaran set web_password=Mobil where web_password is null
Go
update bimaran set web_username=ltrim(rtrim(str(code_bimar)))+ltrim(rtrim(str(code_bimar))) where  len(ltrim(rtrim(web_username))) < 6
Go
update bimaran set web_password=ltrim(rtrim(str(code_bimar)))+ltrim(rtrim(str(code_bimar))) where  len(ltrim(rtrim(web_password))) < 6
Go
--  select web_username,count(*) as tedad from bimaran group by web_username order by tedad DESC
-- select web_password,count(*) as tedad from bimaran group by web_password order by tedad DESC

-- 1396/04/15
Go
ALTER TABLE [dbo].[bimaran]
   add [code_moshtari][int] NULL
Go
ALTER TABLE [dbo].[vaght_dehi]
   add [code_morajeh][int] NULL
Go
ALTER TABLE [dbo].[settinga]
  add [complexity_password] [bit] NULL
Go
-- update settinga set complexity_password=0 
Go
--1396/04/24
ALTER TABLE [dbo].[users]
   add [ab_tekrar_vaght][bit] NULL
Go
update users set ab_tekrar_vaght=0 where ab_tekrar_vaght is null
GO
--1396/05/14
GO

ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_pezeshk] [money] NULL
 Go
ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_azad] [money] NULL
 Go

ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_mabeh] [money] NULL
 Go
 
ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_bimar] [money] NULL
 Go

ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_bimeh] [money] NULL
 Go

ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_yaraneh] [money] NULL
 Go

ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_mokammel] [money] NULL
 Go
	
	ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_takhfif] [money] NULL
 Go
 
 	ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_bed] [money] NULL
 Go
 
 	ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_bes] [money] NULL
 Go
 
 ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_bes_darsad] [money] NULL
 Go
 

 ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [r_bimeh_darsad] [money] NULL
 Go

 
 ALTER TABLE [dbo].[pezeshkan_darsad_bakhsh]
   add [tedad_darman] [int] NULL
 Go

--1396/06/02

Go
 ALTER TABLE [dbo].[Auto_SMS]
   add [sdate] [char](10) NULL
Go
 ALTER TABLE [dbo].[Auto_SMS]
   add [edate] [char](10) NULL
Go
ALTER TABLE [dbo].[Auto_SMS]
  add [stime] [char](5) NULL
Go
ALTER TABLE [dbo].[Auto_SMS]
  add [etime] [char](5) NULL
Go

--1396/06/08

CREATE VIEW [dbo].[sms]
AS
SELECT        id, SMS_Mobile AS sms_num, SMS_MSG AS sms_msg, SendAnswer AS code_send
FROM            dbo.Auto_SMS
WHERE        (SendAnswer <= 0) OR
                         (SendAnswer IS NULL)

GO

ALTER TABLE [dbo].[noskhehha]
  add [code_shift] [smallint] NULL
Go

-- 1396/06/22
Go
 ALTER TABLE [dbo].[bimaran]
   add [code_bimar_moraf] [int] NULL
 Go

GO
INSERT INTO babat_sms (code_babat,name_babat) VALUES (1,N' تاريخ تولد')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (2,N' بدهي چند ماهه')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (3,N' وقت دهي فردا')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (4,N' وقت دهي امروز')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (5,N' يادآوري دوره اي')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (6,N' درمانهاي ناتمام ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (7,N' وقتهاي فردا پزشك ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (8,N' كليه وقتهاي فردا پزشك')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (10,N' دريافت صندوق ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (11,N' پايان شيفت ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (12,N' كلي بيماران ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (9,N' كاركرد ديروز ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (13,' يادآوري دوره اي ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (14,N' اطلاع تشكيل پرونده ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (15,N' بيماران نيامده سيستم وقت دهي ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (16,N' نظرخواهي رضايت از درمان يا كار انجام شده ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (17,N' ارسال دستي ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (18,N' كاركرد ديروز بيمار براي بيمار ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (19,N' كاركرد ديروز پزشك براي پزشك ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (20,N' اطلاع پزشک معرف از ارجاع درمان ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (21,N' کنسلي وقت به بيمار')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (22,N' کنسلي وقت به پزشک')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (23,N' سر رسيد چک امروز تا سه روز اينده')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (24,N' بدهي بيمار بعد از چند روز مشخص')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (25,N' تشکر از تماس شما')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (26,N' وقتهاي کلي فرداي  هر پزشک براي مديريت')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (27,N' کارکرد ديروز هر پزشک براي مديريت')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (28,N' تخفیف اعتباری گروهی')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (29,N' اطلاع به معرف بابت معرفی کردن   ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (30,N' اطلاع میزان تخفیف به معرف بابت معرفی  ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (31,N' اطلاع به معرفی شده بابت معرفی    ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (32,N' وقت های چند روز اینده ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (33,N' کنسلی کلی وقت ها ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (34,N' پیامک رعایت نکات برای هر درمان  ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (35,N' تخفیف اعتباری هدیه اعیاد   ')
Go
INSERT INTO babat_sms (code_babat,name_babat) VALUES (36,N' اطلاع تشکیل پرونده منفی ')
Go

ALTER TABLE [dbo].[settinga]
  add [code_bakhsh_sandogh] [int] NULL
Go

CREATE VIEW [dbo].[update_code_shift_noskheha_with_code_shift_morajeat]
AS
SELECT        dbo.noskhehha.code_noskheh, dbo.noskhehha.code_shift, dbo.morajeat.code_morajeh, dbo.morajeat.code_shift AS code_shift_new
FROM            dbo.noskhehha INNER JOIN
                         dbo.morajeat ON dbo.noskhehha.code_noskheh = dbo.morajeat.code_noskheh

GO

update [dbo].[update_code_shift_noskheha_with_code_shift_morajeat] set code_shift=code_shift_new

Go
-- 1396/06/24
Go
CREATE TABLE [dbo].[settingb](
	[id] [int] NOT NULL,
	[sms_to_moraf_for_introduction] [bit] NULL,
	[sms_to_moraf_amount_of_credit] [bit] NULL,
 CONSTRAINT [PK_settingb] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[settingb] ([id], [sms_to_moraf_for_introduction], [sms_to_moraf_amount_of_credit]) VALUES (1, 0, 0)
Go
-- update settingb set sms_to_moraf_for_introduction=1
-- update settingb set sms_to_moraf_for_introduction=0

Go
ALTER TABLE [dbo].[settingb]
   add [sms_to_moraf_shodeh_for_introduction] [bit] NULL
Go

-- update settingb set sms_to_moraf_shodeh_for_introduction=1
-- update settingb set sms_to_moraf_shodeh_for_introduction=0
-- update settingb set sms_to_moraf_amount_of_credit=1 
-- update settingb set sms_to_moraf_amount_of_credit=0

Go
ALTER TABLE [dbo].[settingb]
   add [active_takhfif_etebari_moraf] [bit] NULL
Go
-- update settingb set active_takhfif_etebari_moraf=1
-- update settingb set active_takhfif_etebari_moraf=0

ALTER TABLE [dbo].[Anbar_Itm_Copy_Past]
  add [code_noa_kala] [int] NULL
Go
ALTER TABLE [dbo].[settingb]
   add [sms_to_moraf_shodeh_for_introduction] [bit] NULL
Go
ALTER TABLE [dbo].[settingb]
   add [code_darman_takhfif_for_moaref] [int] NULL
Go
ALTER TABLE [dbo].[settingb]
   add [code_darman_takhfif_for_moarefi_shode] [int] NULL
Go
update settingb set  code_darman_takhfif_for_moaref=-1112 where code_darman_takhfif_for_moaref is null
Go
update settingb set  code_darman_takhfif_for_moarefi_shode=-1113 where code_darman_takhfif_for_moarefi_shode is null
Go
ALTER TABLE [dbo].[settingb]
   add [alarm_on_sabte_takhfif_moaref] [bit] NULL
Go
update settingb set alarm_on_sabte_takhfif_moaref=0 where alarm_on_sabte_takhfif_moaref is null
Go
-- 1396/07/04
Go
ALTER TABLE [dbo].[settingb]
   add [Ghalam_Noori_pen_width] [int] NULL
Go
ALTER TABLE [dbo].[settingb]
   add [Ghalam_Noori_Active_Paint] [bit] NULL
Go
ALTER TABLE [dbo].[settingb]
   add [Ghalam_Noori_Temp_Number] [int] NULL
Go
update settingb set Ghalam_Noori_pen_width=1 where Ghalam_Noori_pen_width is null
Go
update settingb set Ghalam_Noori_Active_Paint=0 where Ghalam_Noori_Active_Paint is null
Go
update settingb set Ghalam_Noori_Temp_Number=1 where Ghalam_Noori_Temp_Number is null
Go

Go
ALTER TABLE [dbo].[settingb]
   add [Dental_Ad_Ch] [int] NULL
  Go
ALTER TABLE [dbo].[settingb]
   add [Dental_Uni_Qua] [int] NULL
 Go
 update settingb set Dental_Ad_Ch=0 where Dental_Ad_Ch is null 
 Go
 update settingb set Dental_Uni_Qua=0 where Dental_Uni_Qua is null 
Go
ALTER TABLE [dbo].[settingb]
   add [check_to_add_sh_bimeh] [bit] NULL
 Go
ALTER TABLE [dbo].[settingb]
   add [checkup_font_size] [int] NULL
Go
update settingb set checkup_font_size=10 where checkup_font_size is null

Go


ALTER TABLE [dbo].[morajeat]
   add [UR] [char] (20) NULL 
 Go
 ALTER TABLE [dbo].[morajeat]
   add [UL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[morajeat]
   add [LL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[morajeat]
   add [LR] [char] (20) NULL 
 Go

ALTER TABLE [dbo].[settingb]
   add [show_dental_chart] [bit] NULL
 Go
 update settingb set show_dental_chart=0 where show_dental_chart is null

-- update settingb set show_dental_chart=1

ALTER TABLE [dbo].[settingb]
   add [show_dental_tarh_after_insert] [bit] NULL
 Go
  update settingb set show_dental_tarh_after_insert=0 where show_dental_tarh_after_insert is null
  Go
 -- update settingb set show_dental_tarh_after_insert=1
  Go
ALTER TABLE [dbo].[settingb]
   add [sms_talvalod_adalt] [nvarchar](500) NULL
 Go
  update settingb set 
  sms_talvalod_adalt=' update settingb set  sms_talvalod_adalt = '  
  where sms_talvalod_adalt is null
  Go

ALTER TABLE [dbo].[settingb]
   add [SMS_Tabrik_Tashkil_Parvandeh_2] [bit] NULL
 Go
 -- update settingb set SMS_Tabrik_Tashkil_Parvandeh_2=1
 Go

ALTER TABLE [dbo].[settingb]
   add [Tabrik_Tashkil_Parvandeh_text_2] [nvarchar](500) NULL
 Go
  
  update settingb set 
  Tabrik_Tashkil_Parvandeh_text_2='update settingb set  Tabrik_Tashkil_Parvandeh_text_2=  .'  
  where Tabrik_Tashkil_Parvandeh_text_2 is null
  Go



ALTER TABLE [dbo].[settingb]
   add [mablagh_takhfif_tavalod]  [money] NULL 
 Go
update settingb set mablagh_takhfif_tavalod=0 where mablagh_takhfif_tavalod is null
Go

-- مهم
--  اگر مبلغ تخفیف تولد بزرگتر از صفر باشد براش تخفیف لحاظ میشود
---
--SMS_Tarikh_Tavalod=1  

-- update settingb set mablagh_takhfif_tavalod=0
 Go
ALTER TABLE [dbo].[settingb]
   add [code_darman_takhfif_tavalod] [int] NULL
Go
update settingb set  code_darman_takhfif_tavalod=-1114 where code_darman_takhfif_tavalod is null
Go

ALTER TABLE [dbo].[settingb]
   add [mycam_path] [nvarchar](200) NULL
 Go

 --1396/09/24

ALTER TABLE [dbo].[settingb]
   add [Enable_Pish_Pardakht] [bit] NULL
 Go

update settingb set Enable_Pish_Pardakht=1 where Enable_Pish_Pardakht is null
 Go

 --1396/10/02

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[setting_a_sms](
	[id] [int] NOT NULL,
	[cancel_vaght_prefix_txt] [nvarchar](500) NULL,
	[cancel_vaght_name_person] [bit] NULL,
	[cancel_vaght_first_txt] [nvarchar](500) NULL,
	[cancel_vaght_last_txt] [nvarchar](500) NULL,
 CONSTRAINT [PK_setting_a_sms] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[setting_a_sms] ([id], [cancel_vaght_prefix_txt], [cancel_vaght_name_person], [cancel_vaght_first_txt], [cancel_vaght_last_txt]) VALUES (1, N'همکار گرامی', 1, N' وقت داده شده بشما', N'  کنسل شد لطفا با شماره .... تماس بگیرید')
Go
-- update setting_a_sms set cancel_vaght_prefix_txt=N'همکار گرامی'  ,
-- cancel_vaght_name_person=1,
-- cancel_vaght_first_txt=N' وقت داده شده بشما ',
-- cancel_vaght_last_txt= N'کنسل شد لطفا با شماره .... تماس بگیرید '



ALTER TABLE [dbo].[In_Out_Person]
   add [Auto_Add] [bit] NULL
 Go
 update In_Out_Person set Auto_Add=1 where Auto_Add is null
 Go


-- 1396/11/06

ALTER TABLE [dbo].[morajeat]
   add [darsad_pezeshk] [int] NULL
   Go
   update morajeat set darsad_pezeshk=0 where darsad_pezeshk is null
   Go




ALTER TABLE [dbo].[settingb]
   add [Use_Secured_Email] [bit] NULL
 Go
 update settingb set Use_Secured_Email=1 where Use_Secured_Email is null
 Go
ALTER TABLE [dbo].[settingb]
   add [Use_Secured_Email01] [bit] NULL
 Go
 update settingb set Use_Secured_Email01=1 where Use_Secured_Email01 is null
 Go

-- 1396/11/14

ALTER TABLE [dbo].[settingb]
   add [show_fizio_paziresh] [bit] NULL
 Go
-- Update settingb set show_fizio_paziresh=1 
ALTER TABLE [dbo].[settingb]
   add [show_adam_mohasebe_dar_karkerd] [bit] NULL
 Go
-- Update settingb set show_adam_mohasebe_dar_karkerd=1 

ALTER TABLE [dbo].[settingb]
   add [show_Not_Finished] [bit] NULL
Go

 -- Update settingb set show_Not_Finished=1


-- 1396/11/16

ALTER TABLE [dbo].[users]
   add [show_paziresh] [bit] NULL 
Go
update Users set show_paziresh=1 where show_paziresh is null
Go

-- 1396/11/28
ALTER TABLE [dbo].[vaght_dehi]
   add [time_in] [int] NULL 
Go

---- 1396/12/02

ALTER TABLE [dbo].[users]
   add [ab_edit_active_bimar] [bit] NULL 

Go

ALTER TABLE [dbo].[settingb]
   add [check_Active_Bimar_for_Vaghtdehi] [bit] NULL
Go

-- update settingb set check_Active_Bimar_for_Vaghtdehi=1

Go

ALTER TABLE [dbo].[settingb]
   add [check_Active_Bimar_for_Paziresh] [bit] NULL
Go

-- update settingb set check_Active_Bimar_for_Paziresh=1

Go

---- 1396/12/06

ALTER TABLE [dbo].[Auto_SMS]
   add [code_bimar_morafei_shodeh] [int] NULL 
Go

--- 1396/12/10

ALTER TABLE [dbo].[recive_sms]
   add [taeid_ersal_be_web] [bit] NULL
Go
ALTER TABLE [dbo].[recive_sms]
   add [ersal_be_web] [bit] NULL
Go

--   برای سند اختتامیه 
DROP VIEW [dbo].[s_bimeh]
Go

CREATE VIEW [dbo].[s_bimeh]
AS
SELECT        dbo.bimeha.code_bimeh, dbo.bimeha.name_bimeh, dbo.morajeat.r_bes, dbo.morajeat.r_bimeh, dbo.morajeat.r_mokammel, dbo.morajeat.tarikh, 
                         dbo.morajeat.code_user_insert, dbo.morajeat.code_shift
FROM            dbo.bimeha RIGHT OUTER JOIN
                         dbo.morajeat ON dbo.bimeha.code_bimeh = dbo.morajeat.code_bimeh

GO

DROP VIEW [dbo].[s_pezeshkan]
Go
CREATE VIEW [dbo].[s_pezeshkan]
AS
SELECT        dbo.morajeat.r_azad, dbo.morajeat.r_mabeh, dbo.morajeat.r_bimar, dbo.morajeat.r_bimeh, dbo.morajeat.r_yaraneh, dbo.morajeat.r_mokammel, 
                         dbo.morajeat.r_takhfif, dbo.morajeat.r_bed, dbo.morajeat.r_bes, dbo.morajeat.tarikh, dbo.pezeshkan.darsad, dbo.pezeshkan.code_pezeshk, 
                         dbo.morajeat.code_user_insert, dbo.pezeshkan.name_pezeshk, dbo.morajeat.code_shift, (dbo.morajeat.r_bes + dbo.morajeat.r_bimeh) 
                         * dbo.pezeshkan.darsad / 100 AS karkard_dr
FROM            dbo.morajeat LEFT OUTER JOIN
                         dbo.pezeshkan ON dbo.morajeat.code_pezeshk = dbo.pezeshkan.code_pezeshk

GO
-- 1397/02/02
ALTER TABLE [dbo].[users]
   add [ab_edit_fastreport] [bit] NULL 

Go
-- 1397/02/06
ALTER TABLE [dbo].[morajeat_filter]
   add [tarikh_emroz] [char](10) NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [code_shift] [char](10) NULL 
Go

-- 1397/02/08

ALTER TABLE [dbo].[bimaran]
   add [code_shift] [int] NULL 
Go




Go
update setting set onvan_latin='No Name 1397/02/02 '  where onvan_latin is null 
Go
update setting set Email_ID_Support='alichid@gmail.com'  where Email_ID_Support is null
Go
update setting set Email_ID_Manager='alichid@gmail.com'  where Email_ID_Manager is null
Go
update setting set  Email_ID_Sender='info@needsoft.info'  ,  Email_Pass_Sender='9x22OjCo3{'  
Go
update setting set Email_SMTP='mail.needsoft.info'  
Go
update setting set Email_Port='25'  
Go
 update settingb set Use_Secured_Email=1
Go


update setting set Email_ID_Sender01='kohpBogfftqgv/kohp'   
Go
update setting set Email_Pass_Sender01='9x22OjCo3{'
Go
update setting set Email_Port01='46'   
Go
update setting set Email_SMTP01='obkm0ogfftqgv/kohp'
Go
update setting set Email_ID_To01='cmkdjjfAincjn/epo'
Go
update settingb set Use_Secured_Email01=1
Go

UPDATE  setting SET adam_check_and_send_modir=0
Go
 update setting set adam_ersal_email=0
Go


update setting set Last_Edit_Time='2016/06/08'
Go
update hesab set Bed_Old=Bed , Bes_old=Bes
Go
update morajeat set code_bimar=code_bimar_0 where code_bimar=0 and code_bimar_0 > 0
Go
update morajeat set code_pezeshk=code_pezeshk_0 where code_pezeshk=0 and code_pezeshk_0 > 0
Go
update morajeat set code_darman=code_darman_0 where code_darman=0 and code_darman_0 > 0
Go
update setting set adam_ersal_email=0
Go
update setting set adam_check_and_send_modir=0 
Go
-- update setting set version=13970518
Go
UPDATE setting set nasbe_sys=''
Go
UPDATE setting set Entrance_Data=0
Go


--- 1397/02/10

Go
update bimaran set tavalod='13'+tavalod  where LEN(RTRIM(Ltrim(tavalod)))=8 
Go
-- select code_bimar,name,famil,tavalod from bimaran where LEN(RTRIM(Ltrim(tavalod)))<> 10  order by tavalod
Go

delete morajeat_filter
Go
insert morajeat_filter (code_user,tarikh_from,tarikh_to) values (1,'1397/01/01','1398/01/01')

Go



ALTER TABLE [dbo].[tarhe_darman]
   add [r_mokammel] [money] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [r_yaraneh] [money] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [r_pezeshk] [money] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [r_mabeh] [money] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [r_takhfif] [money] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [r_bed] [money] NULL 
Go

--- 1397/03/01

ALTER TABLE [dbo].[settingb]
   add [show_last_tozihat_morajeat] [bit] NULL
Go
-- update settingb set show_last_tozihat_morajeat=1 
ALTER TABLE [dbo].[noskhehha]
  add [serialn] [nvarchar](20) NULL
Go

ALTER TABLE [dbo].[noskhehha]
  add [send_web] [bit] NULL
Go

ALTER TABLE [dbo].[noskhehha]
  add [send_web_sharh] [nvarchar](500) NULL
Go

--1397/03/08

ALTER TABLE [dbo].[tarhe_darman]
   add [code_bimeh] [int] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [code_bakhsh] [int] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [code_pezeshk] [int] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [code_dastyar] [int] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [code_takhasos] [int] NULL 
Go

ALTER TABLE [dbo].[tarhe_darman]
   add [code_yaraneh] [int] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [code_mokammel] [int] NULL 
Go
ALTER TABLE [dbo].[tarhe_darman]
   add [transfer] [bit] NULL 
Go

ALTER TABLE [dbo].[tarhe_darman]
   add [UR] [char] (20) NULL 
 Go
 ALTER TABLE [dbo].[tarhe_darman]
   add [UL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[tarhe_darman]
   add [LL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[tarhe_darman]
   add [LR] [char] (20) NULL 
 Go

--1397/03/20

ALTER TABLE [dbo].[tarhe_darman]
   add [selected] [bit] NULL 
Go


DROP VIEW [dbo].[View_List_Bedehkaran]
Go
CREATE VIEW [dbo].[View_List_Bedehkaran]
AS
SELECT        code_bimar, SUM(r_bed) AS s_r_bed, SUM(r_bes) AS s_r_bes, SUM(r_bed - r_bes) AS mandeh
FROM            dbo.morajeat
GROUP BY code_bimar

GO


-- 1397/03/22

ALTER TABLE [dbo].[morajeat_filter]
   ALTER COLUMN [code_shift] [int] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [program_code_shift] [int] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [program_code_user] [int] NULL 
Go

-- 1397/04/12
ALTER TABLE [dbo].[tarhe_darman]
   ADD  [darsad_bimar] [float] NULL 
Go

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[morajeat_masraf]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[morajeat_masraf]
GO


CREATE VIEW dbo.morajeat_masraf
AS
SELECT     dbo.morajeat.code_morajeh, dbo.morajeat.tedad_darman, dbo.morajeat.ID_Anbar_Hdr, dbo.darmanha.code_daro, dbo.darmanha.barcode, dbo.morajeat.tarikh
FROM         dbo.morajeat INNER JOIN
                      dbo.darmanha ON dbo.morajeat.code_darman = dbo.darmanha.code_darman

GO

-- 1397/04/16

ALTER TABLE [dbo].[users]
   add [ab_esterdad_paziresh_all] [bit] NULL 

Go


-- 1397/04/30
ALTER TABLE [dbo].[morajeat]
    add [code_labratvar_2] [int]  NULL 
  Go

ALTER TABLE [dbo].[morajeat]
    add [r_labratvar_2] [money] NULL 
  Go

CREATE TABLE [dbo].[settingc] (
	[id] [int] NOT NULL ,
	[sms_ba_tavajoh_be_sharayet_darman] [bit] NULL ,
	[show_r_labratvar2_paziresh] [bit] NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[settingc] WITH NOCHECK ADD 
	CONSTRAINT [PK_settingc] PRIMARY KEY  CLUSTERED 
	(
		[id]
	)  ON [PRIMARY] 
GO


INSERT [dbo].[settingc] ([id], [sms_ba_tavajoh_be_sharayet_darman],[show_r_labratvar2_paziresh]) VALUES ( 1,0,0)
GO

ALTER TABLE [dbo].[settingc]
    add [show_r_labratvar2_paziresh] [bit] NULL 
  Go
-- update settingc set show_r_labratvar2_paziresh=1

CREATE TABLE [dbo].[sms_msg] (
	[id] [int] IDENTITY (1, 1) NOT NULL ,
	[code_ertebat] [nvarchar] (10)  NOT NULL ,
	[day] [int] NOT NULL ,
	[msg] [nvarchar] (1024) NULL ,
	[active] [bit] NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[sms_msg] WITH NOCHECK ADD 
	CONSTRAINT [PK_sms_msg] PRIMARY KEY  CLUSTERED 
	(
		[id]
	)  ON [PRIMARY] 
GO


ALTER TABLE [dbo].[settingc]
    add [negetive_r_mabeh] [bit] NULL 
  Go

-- update settingc set negetive_r_mabeh=1
-- for clinic sabz

-- 1397/07/01

ALTER TABLE [dbo].[settingc]
    add [required_aks_bimar] [bit] NULL 
  Go

-- 1397/07/14
Go
INSERT INTO pos_bank  (code_pos,name_pos,pos_external_file_name,pos_ip,sender_form_class,row_id,active)
     VALUES (1,'bank shahr','shahr.exe','192.168.1.50','TMainForm',1,1)
GO
INSERT INTO pos_bank  (code_pos,name_pos,pos_external_file_name,pos_ip,sender_form_class,row_id,active)
     VALUES (2,'samankish','ProjectTestr.exe','192.200.200.200','TMainForm',1,1)
GO
insert pos_bank(code_pos,name_pos,pos_external_file_name,row_id,active) values (3,'behpardakht mellat','http://127.0.0.1:1024/bpmpospc/service',0,0)
Go

-- 1397/07/16

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_0]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_0]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_1]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_1]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_2]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_2]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_3]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_3]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_4]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_4]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_5]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_5]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_6]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_6]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_7]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_7]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_8]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_8]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_9]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_9]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_10]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_10]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_11]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_11]  [money] NULL 
Go

ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_12]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_12]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_13]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_13]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_14]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_14]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_15]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_15]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_16]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_16]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_17]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_17]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_18]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_18]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_19]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_19]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_20]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_20]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_21]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_21]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_22]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_22]  [money] NULL 
Go


ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_23]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_23]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_24]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_24]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_25]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_25]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_26]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_26]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_27]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_27]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_28]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_28]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_29]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_29]  [money] NULL 
Go



ALTER TABLE [dbo].[morajeat_filter]
   add [name_pay_30]  [nvarchar](20) NULL
Go
ALTER TABLE [dbo].[morajeat_filter]
   add [r_pay_30]  [money] NULL 
Go


-- 1397/08/04

ALTER TABLE [dbo].[settingc]
    add [code_manfi_sabte_sari_bimar] [bit] NULL 
  Go

-- update settingc set code_manfi_sabte_sari_bimar=0

-- 1397/08/20

ALTER TABLE [dbo].[pezeshkan]
    add [code_kol] [nvarchar](10) NULL
  Go
  update pezeshkan set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[pezeshkan]
    add [code_goroh] [nvarchar](10) NULL
  Go
   update pezeshkan set code_goroh='100001' where code_goroh is null
  Go

ALTER TABLE [dbo].[pezeshkan]
    add [code_moein] [nvarchar](10) NULL
  Go
  update pezeshkan set code_moein='100001' where code_moein is null
  Go
------

ALTER TABLE [dbo].[pezeshkan]
    add [code_kol_2] [nvarchar](10) NULL
  Go
  update pezeshkan set code_kol_2='100001' where code_kol_2 is null
  Go
ALTER TABLE [dbo].[pezeshkan]
    add [code_goroh_2] [nvarchar](10) NULL
  Go
  update pezeshkan set code_goroh_2='100001' where code_goroh_2 is null
  Go

ALTER TABLE [dbo].[pezeshkan]
    add [code_moein_2] [nvarchar](10) NULL
  Go
  update pezeshkan set code_moein_2='100001' where code_moein_2 is null
  Go

ALTER TABLE [dbo].[pezeshkan]
    add [code_tafzil_2] [nvarchar](10) NULL
  Go
  update pezeshkan set code_tafzil_2='100001' where code_tafzil_2 is null
  Go
  update pezeshkan set code_tafzil='100001' where code_tafzil is null
  Go
---------

ALTER TABLE [dbo].[pay]
    add [code_kol] [nvarchar](10) NULL
  Go
  update pay set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[pay]
    add [code_goroh] [nvarchar](10) NULL
  Go
  update pay set code_goroh='100001' where code_goroh is null
  Go


ALTER TABLE [dbo].[pay]
    add [code_moein] [nvarchar](10) NULL
  Go
   update pay set code_moein='100001' where code_moein is null
  Go

ALTER TABLE [dbo].[pay]
    add [code_tafzil] [nvarchar](10) NULL
  Go
  update pay set code_tafzil='100001' where code_tafzil is null
  Go


ALTER TABLE [dbo].[bimeha]
    add [code_kol] [nvarchar](10) NULL
  Go
  update bimeha set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[bimeha]
    add [code_goroh] [nvarchar](10) NULL
  Go
  update bimeha set code_goroh='100001' where code_goroh is null
  Go

ALTER TABLE [dbo].[bimeha]
    add [code_moein] [nvarchar](10) NULL
  Go
  update bimeha set code_moein='100001' where code_moein is null
  Go

ALTER TABLE [dbo].[bimeha]
    add [code_tafzil] [nvarchar](10) NULL
  Go
  update bimeha set code_tafzil='100001' where code_tafzil is null
  Go

CREATE TABLE [dbo].[link_hesabdari](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[code_system] [int] NOT NULL,
	[name_system] [nvarchar](50) NOT NULL,
	[from_tarikh] [char](10) NULL,
	[to_tarikh] [char](10) NULL,
	[shomare_sanad] [nvarchar](20) NULL,
	[shobeh] [nvarchar](50) NULL,
	[radif] [int] NOT NULL,
	[f1] [nvarchar](100) NULL,
	[f2] [nvarchar](100) NULL,
	[f3] [nvarchar](100) NULL,
	[f4] [nvarchar](100) NULL,
	[f5] [nvarchar](100) NULL,
	[f6] [nvarchar](100) NULL,
	[f7] [nvarchar](100) NULL,
	[f8] [nvarchar](100) NULL,
	[f9] [nvarchar](100) NULL,
	[f10] [nvarchar](100) NULL,
	[f11] [nvarchar](100) NULL,
	[f12] [nvarchar](100) NULL,
	[f13] [nvarchar](100) NULL,
	[f14] [nvarchar](100) NULL,
	[f15] [nvarchar](100) NULL,
	[f16] [nvarchar](100) NULL,
	[f17] [nvarchar](100) NULL,
	[f18] [nvarchar](100) NULL,
	[f19] [nvarchar](100) NULL,
	[f20] [nvarchar](100) NULL,
 CONSTRAINT [PK_link_hesabdari] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]

Go


ALTER TABLE [dbo].[settingc]
    add [code_system_link_hesabdari] [int] NULL 
  Go

-- 1397/08/26

ALTER TABLE [dbo].[pezeshkan]
   ADD  [darsad_naghd] [float] NULL 
  Go
  update pezeshkan set darsad_naghd=50 where darsad_naghd is null
  Go

ALTER TABLE [dbo].[pezeshkan]
   ADD  [darsad_bimeh] [float] NULL 
  Go
  update pezeshkan set darsad_bimeh=50 where darsad_bimeh is null
  Go
ALTER TABLE [dbo].[settingc]
    add [web_url_send] [nvarchar](200) NULL
  Go

ALTER TABLE [dbo].[settingc]
    add [web_url_send_token] [nvarchar](200) NULL
  Go

ALTER TABLE [dbo].[settingc]
    add [web_url_send_session] [nvarchar](10) NULL
  Go

ALTER TABLE [dbo].[settingc]
    add [web_url_send_code_atf] [nvarchar](10) NULL
  Go

  ALTER TABLE [dbo].[settingc]
    add [web_url_del] [nvarchar](200) NULL
  Go


update settingc set web_url_send='http://acc.needsoft.info/frontend/web/api/save-document'
,web_url_send_token='8ju2ZseiN2UmZCBcVlicEr_Xuk0NrmfR'
,web_url_send_session='1' ,web_url_del='http://acc.needsoft.info/frontend/web/api/delete-document' where web_url_send is null

Go

insert pos_bank(code_pos,name_pos,pos_external_file_name,row_id,active) values (4,'ip pos pasargad','http://192.168.0.132:8181',0,0)

Go

-- 1397/08/29



ALTER TABLE [dbo].[settingc]
    add [code_kol_pezeshkan] [nvarchar](10) NULL
  Go
  update settingc set code_kol_pezeshkan='100001' where code_kol_pezeshkan is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_goroh_pezeshkan] [nvarchar](10) NULL
  Go
  update settingc set code_goroh_pezeshkan='100001' where code_goroh_pezeshkan is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_moein_pezeshkan] [nvarchar](10) NULL
  Go
  update settingc set code_moein_pezeshkan='100001' where code_moein_pezeshkan is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_tafzil_pezeshkan] [nvarchar](10) NULL
  Go
  update settingc set code_tafzil_pezeshkan='100001' where code_tafzil_pezeshkan is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_kol_daramad] [nvarchar](10) NULL
  Go
  update settingc set code_tafzil_pezeshkan='100001' where code_tafzil_pezeshkan is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_goroh_daramad] [nvarchar](10) NULL
  Go
  update settingc set code_goroh_daramad='100001' where code_goroh_daramad is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_moein_daramad] [nvarchar](10) NULL
  Go
  update settingc set code_moein_daramad='100001' where code_moein_daramad is null
  Go

ALTER TABLE [dbo].[settingc]
    add [code_tafzil_daramad] [nvarchar](10) NULL
  Go
  update settingc set code_tafzil_daramad='100001' where code_tafzil_daramad is null
  Go

-- 1397/08/30 

ALTER TABLE [dbo].[settingc]
    add [show_bed_bes_pezeshkan_bimar] [bit] NULL 
  Go

-- update settingc set show_bed_bes_pezeshkan_bimar=1
-- update settingc set show_bed_bes_pezeshkan_bimar=0


 -- update  settingc set code_kol_pezeshkan='1' , code_goroh_pezeshkan='1',  code_moein_pezeshkan='1' , code_tafzil_pezeshkan='1'

 Go

  -- update  settingc set code_kol_daramad='1' , code_goroh_daramad='1',  code_moein_daramad='1' , code_tafzil_daramad='1'

  Go

--1 حسابداری تحت وب نید سافت

  IF NOT EXISTS (SELECT
    *
  FROM link_hesabdari
  WHERE code_system = 1)
BEGIN
  INSERT link_hesabdari (code_system, name_system, radif, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20)
    VALUES (1, ' حسابداری تحت وب نید سافت ', 0, '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'شرح سند ', 'کل', 'گروه ', 'معین', 'تفضیل', 'کد ', 'بدهکار', 'بستانکار')
END

GO

-- 2  حسابدرای سپیدار همکاران سیستم

IF NOT EXISTS (SELECT
    *
  FROM link_hesabdari
  WHERE code_system = 2)
BEGIN
  INSERT link_hesabdari (code_system, name_system, radif, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13)
    VALUES (2, ' حسابدرای سپیدار همکاران سیستم ', 0, 'نوع قلم', 'سند حسابداری شماره سند', 'سند حسابداری تاریخ', 'سند حسابداری توضیحات کل سند', 'اقلام سند حسابداری کد معین', 'اقلام سند حسابداری کد تفصيلي', 'اقلام سند حسابداری بدهکار', 'اقلام سند حسابداری بستانکار', 'اقلام سند حسابداری شرح قلم', 'اقلام سند حسابداری شماره پیگیري', 'اقلام سند حسابداری تاریخ پیگیري', 'IssueEntityName', 'IssueEntityRef')
END

Go

-- 3  نوسا  کارکرد پزشکان

IF NOT EXISTS (SELECT
    *
  FROM link_hesabdari
  WHERE code_system = 3)
BEGIN
  INSERT link_hesabdari (code_system, name_system, radif)
    VALUES (3, N' نوسا  کارکرد پزشکان  ', 0)
END

Go
-- 4 نوسا  کارکرد درامد روزانه
IF NOT EXISTS (SELECT
    *
  FROM link_hesabdari
  WHERE code_system = 4)
BEGIN
  INSERT link_hesabdari (code_system, name_system, radif)
    VALUES (4, N' نوسا  کارکرد درامد روزانه  ', 0)
END

Go
IF NOT EXISTS (SELECT
    *
  FROM link_hesabdari
  WHERE code_system = 5)
BEGIN
  INSERT link_hesabdari (code_system, name_system, radif)
    VALUES (5, N' حسابداری پیوست  ', 0)
END
Go

--  delete link_hesabdari

--   insert link_hesabdari (code_system,name_system,radif,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20)values (1,' حسابداری تحت وب نید سافت ',0,'1','2','3','4','5','6','7','8','9','10','11','12','شرح سند ','کل','گروه ','معین','تفضیل','کد ','بدهکار','بستانکار')
Go
-- insert link_hesabdari (code_system,name_system,radif,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13)values
-- (2,' حسابدرای سپیدار همکاران سیستم ',0,'نوع قلم','سند حسابداری شماره سند','سند حسابداری تاریخ','سند حسابداری توضیحات کل سند','اقلام سند حسابداری کد معین','اقلام سند حسابداری کد تفصيلي','اقلام سند حسابداری بدهکار','اقلام سند حسابداری بستانکار','اقلام سند حسابداری شرح قلم','اقلام سند حسابداری شماره پیگیري','اقلام سند حسابداری تاریخ پیگیري','IssueEntityName','IssueEntityRef') 

Go
 
--  insert link_hesabdari (code_system,name_system,radif)values (3,N' نوسا  کارکرد پزشکان  ',0)

GO

--  insert link_hesabdari (code_system,name_system,radif)values (4,N' نوسا  کارکرد درامد روزانه  ',0)

GO

--insert link_hesabdari (code_system,name_system,radif)values (5,N' حسابداری پیوست  ',0)

Go


  ----
 -- update settingc set required_aks_bimar=1
-- for clinic molla sadra 


-- 1397/09/04



ALTER TABLE [dbo].[bank]
    add [code_kol] [nvarchar](10) NULL
  Go
  update bank set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[bank]
    add [code_goroh] [nvarchar](10) NULL
  Go
  update bank set code_goroh='100001' where code_goroh is null
  Go

ALTER TABLE [dbo].[bank]
    add [code_moein] [nvarchar](10) NULL
  Go
  update bank set code_moein='100001' where code_moein is null
  Go

ALTER TABLE [dbo].[bank]
    add [code_tafzil] [nvarchar](10) NULL
  Go
  update bank set code_tafzil='100001' where code_tafzil is null
  Go


Go
ALTER TABLE [dbo].[users]
    add [ab_Not_finished] [bit] NULL
 Go

-- 1397/09/12 
ALTER TABLE [dbo].[pezeshkan]
   ADD  [karkerd_sahme_pezeshk] [bit] NULL 
  Go


CREATE TABLE [dbo].[vaght_dehi_cancel] (
	[id] [int] IDENTITY (1, 1) NOT NULL ,
	[code_vaght_dehi] [int] NOT NULL ,
	[sharh] [nvarchar] (500)  NOT NULL ,
	[tarikh_c] [char] (10)  NOT NULL ,
	[saat_c] [char] (5)  NOT NULL ,
	[tarikh] [char] (10)  NOT NULL ,
	[post_time] [datetime] NOT NULL ,
	[code_bimar] [int] NOT NULL ,
	[code_pezeshk] [int] NULL ,
	[code_bakhsh] [int] NULL ,
	[code_user] [int] NOT NULL ,
	[code_shift] [int] NULL ,
	[code_shobeh] [int] NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[vaght_dehi_cancel] WITH NOCHECK ADD 
	CONSTRAINT [PK_vaght_dehi_cancel] PRIMARY KEY  CLUSTERED 
	(
		[id]
	)  ON [PRIMARY] 
GO



ALTER TABLE [dbo].[settingc]
    add [sabte_cancel_vaght_dehi] [bit] NULL 
  Go

--  update settingc set sabte_cancel_vaght_dehi=1
--  update settingc set sabte_cancel_vaght_dehi=0


--  1397/09/18
ALTER TABLE [dbo].[settingc]
    add [code_pay_adam_mohasebe_hesabdari] [nvarchar](100) NULL
  Go

  ALTER TABLE [dbo].[settingc]
    ALTER COLUMN [code_pay_adam_mohasebe_hesabdari] [nvarchar](100) NULL
  Go

  --  عدم محاسبه در کارکرد  لینک حسابداری 
--  update settingc set code_pay_adam_mohasebe_hesabdari=' and code_pay<> 5 and code_pay<>6  and code_pay <> 9 '
--  update settingc set code_pay_adam_mohasebe_hesabdari=' and code_pay<> 5 '
--  update settingc set code_pay_adam_mohasebe_hesabdari=''



ALTER TABLE [dbo].[darmanha]
    add [code_kol] [nvarchar](10) NULL
  Go
  update darmanha set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[darmanha]
    add [code_goroh] [nvarchar](10) NULL
  Go
  update darmanha set code_goroh='100001' where code_goroh is null
  Go

ALTER TABLE [dbo].[darmanha]
    add [code_moein] [nvarchar](10) NULL
  Go
  update darmanha set code_moein='100001' where code_moein is null
  Go

ALTER TABLE [dbo].[darmanha]
    add [code_tafzil] [nvarchar](10) NULL
  Go
  update darmanha set code_tafzil='100001' where code_tafzil is null
  Go



ALTER TABLE [dbo].[bimeha]
    add [code_tafzil_bimaran] [nvarchar](10) NULL
  Go
  update bimeha set code_tafzil_bimaran='100001' where code_tafzil_bimaran is null
  Go


ALTER TABLE [dbo].[users]
   add [ab_view_tarhe_darman_s] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_insert_tarhe_darman_s] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_del_tarhe_darman_s] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_edit_tarhe_darman_s] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_report_tarhe_darman_s] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_taeid_tarhe_darman_s] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_b_taeid_tarhe_darman_s] [bit] NULL 
Go

ALTER TABLE [dbo].[settingc]
   add [select_pos_bank] [bit] NULL 
Go
-- update settingc set select_pos_bank=1
Go

-- 1397/09/26 

CREATE TABLE [dbo].[vaght_dehi_cancel_ellat] (
	[code_ellat] [int] NOT NULL ,
	[name_ellat] [nvarchar] (50) COLLATE Arabic_CI_AS NOT NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[vaght_dehi_cancel_ellat] WITH NOCHECK ADD 
	CONSTRAINT [PK_vaght_cancel_ellat] PRIMARY KEY  CLUSTERED 
	(
		[code_ellat]
	)  ON [PRIMARY] 

Go
insert vaght_dehi_cancel_ellat(code_ellat,name_ellat)values (1,N'کنسلی توسط پزشک')
Go
insert vaght_dehi_cancel_ellat(code_ellat,name_ellat)values (2,N'کنسلی توسط بیمار')
Go
insert vaght_dehi_cancel_ellat(code_ellat,name_ellat)values (3,N'کنسلی توسط ...')
Go


ALTER TABLE [dbo].[settingc]
   add [vaght_dehi_cancel_ellat] [int] NULL 
Go

ALTER TABLE [dbo].[vaght_dehi_cancel]
   add [code_ellat] [int] NULL 
Go


ALTER TABLE [dbo].[users]
   add [ab_edit_mablagh_pos] [bit] NULL 
Go
update users set ab_edit_mablagh_pos=1 where ab_edit_mablagh_pos is Null
Go

ALTER TABLE [dbo].[settingc]
   add [limit_vaght_dehi_darmanha] [bit] NULL 
Go
-- update settingc set limit_vaght_dehi_darmanha=1
Go
-- 1397/10/06
--  لیست محدودیت وقت دهی    بیشتر از  10 روز وقت ایمپلنت داده نشود

CREATE TABLE [dbo].[vaght_dehi_limit] (
	[code_ertebat] [nvarchar] (10)  NOT NULL ,
	[tedad_roze] [int] NOT NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[vaght_dehi_limit] WITH NOCHECK ADD 
	CONSTRAINT [PK_vaght_dehi_limit] PRIMARY KEY  CLUSTERED 
	(
		[code_ertebat]
	)  ON [PRIMARY] 
GO


-- 1397/10/06
-- پزشک بیشتر از 1 کنسلی برای یک بیمار نداشته باشد
ALTER TABLE [dbo].[settingc]
   add [limit_cancel_vaght_dehi_pezeshk] [int] NULL 
Go
 update settingc set limit_cancel_vaght_dehi_pezeshk=999  where limit_cancel_vaght_dehi_pezeshk is null
-- update settingc set limit_cancel_vaght_dehi_pezeshk=0
Go 


-- -- 1397/10/10
--  الزام ثبت پوز بانکی  لیست واریز به حساب 
ALTER TABLE [dbo].[settingc]
   add [elzam_sabte_detial_pos_paziresh] [bit] NULL 
Go

-- update settingc set elzam_sabte_detial_pos_paziresh=0
-- update settingc set elzam_sabte_detial_pos_paziresh=1

--  مشاهده صفحه واریز به حساب بانکی  در پذیرش 
ALTER TABLE [dbo].[settingc]
   add [show_Variz_Be_Hesab_Banki_paziresh] [bit] NULL 
Go

 update settingc set show_Variz_Be_Hesab_Banki_paziresh=1 where show_Variz_Be_Hesab_Banki_paziresh is null

 Go
-- update settingc set show_Variz_Be_Hesab_Banki_paziresh=0
-- update settingc set show_Variz_Be_Hesab_Banki_paziresh=1


-- 1397/10/14
-- مهم
--  اگر مبلغ تخفیف تولد بزرگتر از صفر باشد براش تخفیف لحاظ میشود
-- SMS_Tarikh_Tavalod=1  
-- update settingb set mablagh_takhfif_tavalod=0


--  هدیه جهت اعیاد 
-- مشخص شدن روز هدیه
--  هدیه جهت اعیاد وابسته به  پیامک تاریخ تولد و هدیه تاریخ تولد است  
ALTER TABLE [dbo].[settingc]
   add [active_takhfif_eid] [bit] NULL
Go
-- فعال کردن تخفیف عید 
-- update settingc set active_takhfif_eid=1
--  مشخص کردن بیمارانی که تخفیف عید انجام نشود 
ALTER TABLE [dbo].[bimaran]
   add [not_takhfif_eid] [bit] NULL
Go
 


--
ALTER TABLE [dbo].[tarikh]
   add [hedyeh] [bit] NULL 
Go
-- مبلغ هدیه
ALTER TABLE [dbo].[tarikh]
   add [mablagh_hedyeh] [money] NULL 
Go
--  متن هدیه
ALTER TABLE [dbo].[tarikh]
   add [text_hedyeh] [nvarchar](500) NULL
Go
-- update tarikh set text_hedyeh='عید شما میارک . مبلغ 200 تومان هدیه به شما تعلق گرفته - مرکز خیلی خوب  خوبان' where tarikh='1390/01/01'
Go

ALTER TABLE [dbo].[settingc]
   add [code_darman_takhfif_eid] [int] NULL
Go
update settingc set  code_darman_takhfif_eid=-1119 where code_darman_takhfif_eid is null
Go
ALTER TABLE [dbo].[settingc]
   add [sms_takhfif_eid] [bit] NULL
Go
-- update settingc set sms_takhfif_eid=1

Go


-- -- 1397/10/22
CREATE TABLE [dbo].[transaction_log](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[babat_sabt] [int] NULL,
	[transaction_name] [nvarchar](100) NULL,
	[transaction_tarikh] [nvarchar](10) NULL,
	[transaction_date] [datetime] NULL,
	[transaction_error] [int] NULL,
	[transaction_detail] [nvarchar](100) NULL,
	[transaction_tedad] [int] NULL,
 CONSTRAINT [PK_transaction_log] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO

---------------------------------------------------------------
-- فقط sql2014

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_insert_hedyeh_morajeat' AND type = 'P')
   DROP PROCEDURE sp_insert_hedyeh_morajeat
GO

/****** Object:  StoredProcedure [dbo].[sp_insert_hedyeh_morajeat]    Script Date: 1/8/2019 14:31:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_insert_hedyeh_morajeat]
	-- Add the parameters for the stored procedure here
(
	@name nvarchar(100) ,
	@tarikh nvarchar(10),
	@r_takhfif money,
	@send_sms bit,
	@babat_sms int,
	@babat_sabt int,
	@sharh_darman varchar(1000),
	@tozihat varchar(1000),
	@code_user_insert int,
	@code_shift int,
	@code_bimeh int,
	@code_bakhsh int,
	@code_pezeshk int,
	@code_darman int,
	@sms_msg nvarchar(1024)
	--@tedad_morajeh int output,
	--@tedad_sms int output
)
AS
BEGIN

	BEGIN TRANSACTION hedyeh;
	BEGIN TRY

	Declare @r_bed money = (-1 * @r_takhfif);
	Declare @tedad_darman int = 1;
	Declare @insert_time datetime = GETDATE();
	Declare @r_azad money = 0;
	Declare @r_bimeh money = 0;
	Declare @r_bimar money = 0;
	Declare @r_mabeh money = 0;
	Declare @r_bes money = 0;
	Declare @r_yaraneh money = 0;
	Declare @r_mokammel money = 0;
	Declare @r_pezeshk money = 0;
	Declare @code_yaraneh int = 0;
	Declare @code_mokammel int = 0;
	Declare @code_dastyar int = 0;
	Declare @code_pay int = 0;
	Declare @r_mandeh money = 0;
	Declare @code_noskheh int = 0;
	Declare @ID_Anbar_HDR int = 0;
	Declare @code_labratvar int = 0;
	Declare @code_sabt_daem_darman int = 0;
	Declare @saat varchar(5) = CONVERT(char(5),GETDATE(),108);

	
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;


	

	

		--BEGIN TRANSACTION hedyeh
		-- Insert statement for procedure here
		INSERT into morajeat(code_bimar, tarikh, r_bed, r_takhfif, tedad_darman, sharh_darman, tozihat, insert_time, code_user_insert, code_shift,
							 code_bimeh, code_bakhsh, code_pezeshk, code_darman, r_azad, r_bimeh, r_bimar, r_mabeh, r_bes, r_yaraneh,
							 r_mokammel, r_pezeshk, code_yaraneh, code_mokammel, code_dastyar, code_pay, r_mandeh, code_noskheh, 
							 ID_Anbar_Hdr, code_labratvar, code_sabt_daem_darman)
		SELECT code_bimar, @tarikh, @r_bed, @r_takhfif, @tedad_darman, @sharh_darman, @tozihat, @insert_time, @code_user_insert, @code_shift,
							 @code_bimeh, @code_bakhsh, @code_pezeshk, @code_darman, @r_azad, @r_bimeh, @r_bimar, @r_mabeh, @r_bes, @r_yaraneh,
							 @r_mokammel, @r_pezeshk, @code_yaraneh, @code_mokammel, @code_dastyar, @code_pay, @r_mandeh, @code_noskheh, 
							 @ID_Anbar_Hdr, @code_labratvar, @code_sabt_daem_darman
		FROM bimaran  
		WHERE ( Active <> 0 ) and ( not_takhfif_eid = 0 or not_takhfif_eid is null ) 
		ORDER BY code_bimar

		--SET @tedad_morajeh = @@ROWCOUNT;

		INSERT INTO transaction_log 
		SELECT @babat_sabt, @name, @tarikh, @insert_time, @@ERROR, @tarikh + ' - mablagh: ' + cast( @r_takhfif as nvarchar )+ ' - tedad: ' + cast(@@ROWCOUNT as nvarchar) + ' - ' + 'Transaction Success', @@ROWCOUNT
	
		IF (@send_sms = 1)
		BEGIN
			BEGIN TRANSACTION sms;
			BEGIN TRY

				INSERT into Auto_SMS(SMS_Mobile, SMS_MSG, tarikh, Saat, code_babat, code_bimar, sdate, edate, stime, etime)
				SELECT Mobil, @sms_msg, @tarikh, @saat, @babat_sms, code_bimar, @tarikh, @tarikh, '08:00', '20:00'
				FROM bimaran  
				WHERE ( Active <> 0 ) and ( not_takhfif_eid = 0 or not_takhfif_eid is null ) and ( LEN(Mobil) > 9 )
				ORDER BY code_bimar

				--SET @tedad_sms = @@ROWCOUNT;

				INSERT INTO transaction_log 
				SELECT @babat_sms, @name + '_sms', @tarikh, @insert_time, @@ERROR, @tarikh + ' - mablagh: ' + cast( @r_takhfif as nvarchar )+ ' - tedad: ' + cast(@@ROWCOUNT as nvarchar) + ' - ' + 'Transaction Success', @@ROWCOUNT

				COMMIT TRANSACTION sms
			END TRY

			BEGIN CATCH

				ROLLBACK TRANSACTION sms; 

				INSERT INTO transaction_log 
				SELECT @babat_sms, @name + '_sms', @tarikh, @insert_time, 515, @tarikh + ' - mablagh: ' + cast( @r_takhfif as nvarchar )+ ' - tedad: ' + cast(@@ROWCOUNT as nvarchar) + ' - ' + 'Transaction Failed', @@ROWCOUNT

			END CATCH

		END

	COMMIT TRANSACTION hedyeh
	END TRY

	BEGIN CATCH

		ROLLBACK TRANSACTION hedyeh;

		INSERT INTO transaction_log 
		SELECT @babat_sabt, @name, @tarikh, @insert_time, 515 , @tarikh + ' - ' + cast( @r_takhfif as nvarchar ) + ' - mablagh: ' + cast(@@ROWCOUNT as nvarchar) + ' - tedad: ' + 'Transaction Failed', @@ROWCOUNT
    
	END CATCH
    

/*******************************

Description: Insert Records In Tables Morajeat & Auto_SMS   
Author: Golozari Ali - Nobody :) 
Company: NeedSoft 
Create Date: 2019/01/08 - 1397/10/18
Create Time: 14:00
Param: @name, @tarikh, @r_takhfif, @send_sms, @babat_sms, @babat_sabt, @sharh_darman, @tozihat, @code_user_insert, @code_shift 
		@code_bimeh, @code_bakhsh, @code_pezeshk, @code_darman, @sms_msg
Return: No Return Param  
Modified Date: 2019/01/09 - 1397/10/19
Modified Time: 11:40
Modification: 1- Add @sms_msg In Params 
			  2- Add Drop Procedure If Exists
			  3- Change Len Mobile From = 11 To > 9

********************************/  

/********************************
1- For Test => Morajeat
	INSERT into morajeat(code_bimar, tarikh, r_bed, r_takhfif, tedad_darman, sharh_darman, tozihat, insert_time, code_user_insert, code_shift,
								 code_bimeh, code_bakhsh, code_pezeshk, code_darman, r_azad, r_bimeh, r_bimar, r_mabeh, r_bes, r_yaraneh,
								 r_mokammel, r_pezeshk, code_yaraneh, code_mokammel, code_dastyar, code_pay, r_mandeh, code_noskheh, 
								 ID_Anbar_Hdr, code_labratvar, code_sabt_daem_darman)
			SELECT code_bimar, '1397/10/22', -20000, 20000, 1, 'test sharh', 'test tozihat', '2019-01-09 09:17:34.180', 1, 1,
								 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
								 0, 0, 0, 0, 0, 0, 0, 0, 
								 0, 0, 0
			FROM bimaran  
			WHERE ( Active <> 0 ) and ( not_takhfif_eid = 0 or not_takhfif_eid is null ) 
			ORDER BY code_bimar

2- For Test => Auto_SMS
	INSERT into Auto_SMS(SMS_Mobile, SMS_MSG, tarikh, Saat, code_babat, code_bimar, sdate, edate, stime, etime)
					SELECT Mobil, 'test sms', '1397/10/22', '08:00', 99, code_bimar, '1397/10/22', '1397/10/22', '08:00', '20:00'
					FROM bimaran  
					WHERE ( Active <> 0 ) and ( not_takhfif_eid = 0 or not_takhfif_eid is null ) and ( LEN(Mobil) > 9 )
					ORDER BY code_bimar

********************************/


	
END

Go



-- -- 1397/10/24

ALTER TABLE [dbo].[users]
   ADD  [ab_report_bimaran] [bit] NULL  
GO
update users set ab_report_bimaran=1 where ab_report_bimaran is null
Go

-- -- 1397/10/26
ALTER TABLE [dbo].[auto_sms]
   ADD  [SendAnswer2] [nvarchar](1000) NULL  
GO


-- SendAnswer2


IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_mahasebeh_sarjame_noskhehha' AND type = 'P')
   DROP PROCEDURE sp_mahasebeh_sarjame_noskhehha
GO

create PROCEDURE [dbo].[sp_mahasebeh_sarjame_noskhehha]

AS
BEGIN

update noskhehha set 
r_noskheh=(select sum(r_azad) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_bimeh=(select sum(r_bimeh) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_bimar=(select sum(r_bimar) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_takhfif=(select sum(r_takhfif) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_mabeh=(select sum(r_mabeh) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_bed=(select sum(r_bed) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_bes=(select sum(r_bes) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_pezeshk=(select sum(r_pezeshk) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_mokammel=(select sum(r_mokammel) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null )),
r_yaraneh=(select sum(r_yaraneh) from morajeat where code_noskheh=noskhehha.code_noskheh and (not_bimeh = 0 or not_bimeh is null ))

END

Go

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'api_asanak_send_sms_proc' AND type = 'P')
   DROP PROCEDURE api_asanak_send_sms_proc
GO

/****** Object:  StoredProcedure [dbo].[api_asanak_send_sms_proc]    Script Date: 1/15/2019 11:06:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[api_asanak_send_sms_proc]
(
@username varchar(50),
@password varchar(50),
@source varchar(50),
@message nvarchar(1024),
@destination varchar(1024),
@id_sms int
)
AS
DECLARE @vPointer INT,
@vResponseText VARCHAR(8000),
@vStatus INT,
@vStatusText VARCHAR(200),
@Parametres nvarchar(3000),
@requestBody nvarchar(3000),
@res nvarchar(150),
@res_replace nvarchar(150)
-- Must be change on live.
SET @Parametres = ''
SET @Parametres = @Parametres + '&Username=' + @username
SET @Parametres = @Parametres + '&Password=' + @password
SET @Parametres = @Parametres + '&Source=' + @source
SET @Parametres = @Parametres + '&Destination=' + @destination
SET @Parametres = @Parametres + '&message=' + @message

DECLARE @len INT = len(@Parametres)

EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', @vPointer OUTPUT
EXEC sp_OAMethod @vPointer, 'open',NULL, 'POST', 'https://panel.asanak.com/webservice/v1rest/sendsms' , 0
EXEC sp_OAMethod @vPointer, 'setRequestHeader', null, 'Content-Type', 'application/x-www-form-urlencoded'
EXEC sp_OAMethod @vPointer, 'setRequestHeader', null, 'Content-Length', @len
EXEC sp_OAMethod @vPointer, 'Send', NULL, @Parametres
EXEC sp_OAMethod @vPointer, 'Status', @vStatus OUTPUT
EXEC sp_OAMethod @vPointer, 'StatusText', @vStatusText OUTPUT
EXEC sp_OAMethod @vPointer, 'responseText', @vResponseText OUTPUT
EXEC sp_OADestroy @vPointer


SELECT @vResponseText as response , @Parametres as parameteres , @vStatusText as statuses

SET @res = @vResponseText
SET @res_replace = REPLACE(@res, '[','')
SET @res_replace = REPLACE(@res_replace, ']','')

--select @res_replace

IF ( (LEFT(@res, 1) = '[') and (RIGHT(@res, 1) = ']') and (ISNUMERIC(@res_replace) = 1))
BEGIN
	UPDATE Auto_SMS set SendAnswer = 100 ,SendAnswer2 = @vResponseText
	WHERE id = @id_sms and SMS_Mobile = @destination and SMS_MSG = @message
END
ELSE 
BEGIN
	UPDATE Auto_SMS set SendAnswer2 = @vResponseText
	WHERE id = @id_sms and SMS_Mobile = @destination and SMS_MSG = @message
END


/***********************************

Description: Send Sms With Restful Api Asanak   
Author: Golozari Ali - Nobody :) 
Company: NeedSoft 
Create Date: 2019/01/13 - 1397/10/23
Create Time: 18:00
Param: @username, @password, @source, @message, @destination, @id_sms
Return: No Return Param  
Modified Date: 2019/01/15 - 1397/10/25
Modified Time: 15:40
Modification: 1- Add Param @id_sms For Update SendAnswer In Table Auto_SMS 
			  2- Add Update For Send SMS

***********************************/ 
Go
IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_send_sms' AND type = 'P')
   DROP PROCEDURE sp_send_sms
GO

/****** Object:  StoredProcedure [dbo].[sp_send_sms]    Script Date: 1/13/2019 16:42:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_send_sms]
  -- Add the parameters for the stored procedure here
  -- Exec sp_send_sms '1397/10/25', '10:00', 99 , 4, 1,441698
(
  @tarikh nvarchar(10),
  @saat nvarchar(5) ,
  @code_babat int,
  @code_operator int,
  @send_taki bit,
  @id_sms int
  )
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @username nvarchar(100) = 'testasanakns'
	DECLARE @password nvarchar(100) = 'NeedSoft'
	DECLARE @source nvarchar(100) = '982100066389654'
	DECLARE @sms_msg nvarchar(1024)
	DECLARE @sms_mobile nvarchar(50)
	DECLARE @id_auto int

	IF(@send_taki = 0)
	BEGIN

		DECLARE cursor_select_auto_sms CURSOR FAST_FORWARD
		FOR SELECT TOP 10  id,SMS_MSG, SMS_Mobile FROM Auto_SMS 
			WHERE @tarikh BETWEEN sdate AND edate 
				AND @saat BETWEEN stime AND etime 
				AND code_babat = @code_babat
				AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))
			ORDER BY id DESC

		OPEN cursor_select_auto_sms
		FETCH NEXT FROM cursor_select_auto_sms INTO @id_auto, @sms_msg, @sms_mobile

		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC api_asanak_send_sms_proc @username, @password, @source, @sms_msg ,@sms_mobile, @id_auto 
		
			FETCH NEXT FROM cursor_select_auto_sms INTO @id_auto, @sms_msg, @sms_mobile
		END

		CLOSE cursor_select_auto_sms
		DEALLOCATE cursor_select_auto_sms
	END
	ELSE
	BEGIN

		SELECT  @id_auto = id, @sms_msg = SMS_MSG,@sms_mobile = SMS_Mobile FROM Auto_SMS 
			WHERE id = @id_sms
				AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))
		IF (@@ROWCOUNT > 0)
		BEGIN
			EXEC api_asanak_send_sms_proc @username, @password, @source, @sms_msg, @sms_mobile, @id_auto 
		END
		ELSE
		BEGIN
			PRINT('Not Find This ID In SMS Taki SELECT')
		END
	END

/***********************************

Description: Send Sms Taki And Gorohi With Restful Api   
Author: Golozari Ali - Nobody :) 
Company: NeedSoft 
Create Date: 2019/01/13 - 1397/10/23
Create Time: 18:00
Param: @tarikh, @saat, @code_babat, @code_operator, @send_taki, @id_sms
Return: No Return Param  
Modified Date: 2019/01/15 - 1397/10/25
Modified Time: 15:40
Modification: 1- Add Fiture Send Taki 
			  2- Add Drop Procedure If Exists

***********************************/ 

/***********************************

1- For Test => Gorohi
		SELECT TOP 10  SMS_MSG, SMS_Mobile FROM Auto_SMS 
		WHERE '1397/10/25' BETWEEN sdate AND edate 
			AND '10:00' BETWEEN stime AND etime 
			AND code_babat = 99
			AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
			AND ((SendAnswer < 1) or (SendAnswer is null))
		ORDER BY id DESC


2- For Test => Taki
		SELECT   id, SMS_MSG, SMS_Mobile FROM Auto_SMS 
			WHERE id = 441698
				AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))

***********************************/

END

GO


-- 1397/10/28
Go
ALTER TABLE [dbo].[labratvar]
   add [UR] [char] (20) NULL 
 Go
 ALTER TABLE [dbo].[labratvar]
   add [UL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[labratvar]
   add [LL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[labratvar]
   add [LR] [char] (20) NULL 
 Go

---- 1397/11/02

Go
ALTER TABLE [dbo].[settingc]
   add [show_all_record_after_tarikh_paziresh]  [char] (10) NULL
Go
update settingc set show_all_record_after_tarikh_paziresh='1300/01/01' where show_all_record_after_tarikh_paziresh is null
Go
-- 
-- update settingc set show_all_record_after_tarikh_paziresh='1300/01/01'

-- update settingc set show_all_record_after_tarikh_paziresh='1396/12/29'


---- 1397/11/12

ALTER TABLE [dbo].[kala]
    add [code_kol] [nvarchar](10) NULL
  Go
  update kala set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[kala]
    add [code_goroh] [nvarchar](10) NULL
  Go
  update kala set code_goroh='100001' where code_goroh is null
  Go


ALTER TABLE [dbo].[kala]
    add [code_moein] [nvarchar](10) NULL
  Go
   update kala set code_moein='100001' where code_moein is null
  Go

ALTER TABLE [dbo].[kala]
    add [code_tafzil] [nvarchar](10) NULL
  Go
  update kala set code_tafzil='100001' where code_tafzil is null
  Go





ALTER TABLE [dbo].[goroh_kala]
    add [code_kol] [nvarchar](10) NULL
  Go
  update goroh_kala set code_kol='100001' where code_kol is null
  Go

--ALTER TABLE [dbo].[goroh_kala]
 --   add [code_goroh] [nvarchar](10) NULL
--  Go
--  update goroh_kala set code_goroh='100001' where code_goroh is null
 -- Go


ALTER TABLE [dbo].[goroh_kala]
    add [code_moein] [nvarchar](10) NULL
  Go
   update goroh_kala set code_moein='100001' where code_moein is null
  Go

ALTER TABLE [dbo].[goroh_kala]
    add [code_tafzil] [nvarchar](10) NULL
  Go
  update goroh_kala set code_tafzil='100001' where code_tafzil is null
  Go




ALTER TABLE [dbo].[moshtari]
    add [code_kol] [nvarchar](10) NULL
  Go
  update moshtari set code_kol='100001' where code_kol is null
  Go

ALTER TABLE [dbo].[moshtari]
    add [code_goroh] [nvarchar](10) NULL
 Go
 update moshtari set code_goroh='100001' where code_goroh is null
  Go


ALTER TABLE [dbo].[moshtari]
    add [code_moein] [nvarchar](10) NULL
  Go
   update moshtari set code_moein='100001' where code_moein is null
  Go

--1397/11/20

  ALTER TABLE [dbo].[morajeat]
   add [r_takhfif_p] [money] NULL 
Go


-- update darmanha set zarib_k=0,zarib_k_labratvar=0,zarib_k_masraf=0 
-- where zarib_k=1 and zarib_k_labratvar=1 and zarib_k_masraf=1
Go

--  1397/11/24

ALTER TABLE [dbo].[settingc]
   add [start_tarikh_takhfif_etebari]  [char] (10) NULL
Go
 update settingc set start_tarikh_takhfif_etebari='1398/04/01' where start_tarikh_takhfif_etebari is  null
Go
-- update settingc set start_tarikh_takhfif_etebari='1398/04/01'
Go

--  1397/12/10
 ALTER TABLE [dbo].[bimaran]
   add [bedehi_roz] [money] NULL 
Go



ALTER TABLE [dbo].[users]
   add [ab_add_Examination] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_del_Examination] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_edit_Examination] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_view_Examination] [bit] NULL 
Go
ALTER TABLE [dbo].[users]
   add [ab_rep_Examination] [bit] NULL 
Go



-- 1398/02/01

CREATE TABLE [dbo].[Examination] (
	[id] [int] IDENTITY (1, 1) NOT NULL ,
	[code_bimar] [int] NOT NULL ,
	[tarikh] [char] (10)    NOT NULL ,
	[vazn] [float] NULL ,
	[ghad] [float] NULL ,
	[doreshekam] [float] NULL ,
	[dorekamar] [float] NULL ,
	[dorebasan] [float] NULL ,
	[doreran] [float] NULL ,
	[dorebazo] [float] NULL ,
	[bmi] [float] NULL ,
	[code_user_insert] [int] NULL ,
	[insert_time] [datetime] NULL ,
	[code_user_edit] [int] NULL ,
	[edit_time] [datetime] NULL ,
	[code_shift] [int] NULL ,
	[code_shobeh] [int] NULL 
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[ExaminationDetail] (
	[id] [int] IDENTITY (1, 1) NOT NULL ,
	[tarikh] [char] (10)    NOT NULL ,
	[code_bimar] [int] NOT NULL ,
	[BPH] [float] NULL ,
	[BPL] [float] NULL ,
	[Pulse] [int] NULL ,
	[Elat_Tanasob_Andam] [bit] NULL ,
	[Elat_DardMa_fasel] [bit] NULL ,
	[Elat_Sardard] [bit] NULL ,
	[Elat_Zibaei] [bit] NULL ,
	[Elat_Bimari_Post] [bit] NULL ,
	[Elat_Morajeh_Sayer] [nvarchar] (500)    NULL ,
	[Sabeghe_Feshar_Bala] [bit] NULL ,
	[Sabeghe_charbi_khon] [bit] NULL ,
	[Sabeghe_Diabet] [bit] NULL ,
	[Sabeghe_Feshar_Sayer] [nvarchar] (500)    NULL ,
	[Sabeghe_kam_kari_Troeid] [bit] NULL ,
	[Sabeghe_por_kari_Troeid] [bit] NULL ,
	[Sabeghe_ekhtelal_ghaedegi] [bit] NULL ,
	[Sabeghe_ekhtelal_hormon_sayer] [nvarchar] (500)    NULL ,
	[Sabeghe_estemal_sigar] [bit] NULL ,
	[Sabeghe_estemal_mashrob] [bit] NULL ,
	[Sabeghe_estemal_ghelyan] [bit] NULL ,
	[sabeghe_Estelam_hichkodam] [bit] NULL ,
	[sabeghe_ekhtelal_govaresh_dard_medeh] [bit] NULL ,
	[sabeghe_ekhtelal_govaresh_riflaks] [bit] NULL ,
	[sabeghe_ekhtelal_govaresh_nafkh] [bit] NULL ,
	[sabeghe_ekhtelal_govaresh_yobosat] [bit] NULL ,
	[sabeghe_ekhtelal_govaresh_kolit] [bit] NULL ,
	[sabeghe_ekhtelal_govaresh_sayer] [nvarchar] (500)    NULL ,
	[sabeghe_asab_esteres] [bit] NULL ,
	[sabeghe_asab_afsordegi] [bit] NULL ,
	[sabeghe_asab_moshgel_khab] [bit] NULL ,
	[sabeghe_asab_vasvas] [bit] NULL ,
	[sabeghe_asab_sayer] [nvarchar] (500)    NULL ,
	[sabeghe_alerzhi_daroei] [bit] NULL ,
	[sabeghe_alerzhi_ghazaei] [bit] NULL ,
	[sabeghe_alerzhi_nakh_bakhieh] [bit] NULL ,
	[sabeghe_alerzhi_felezat] [bit] NULL ,
	[sabeghe_alerzhi_hichkodam] [bit] NULL ,
	[sabeghe_teb_sozani_yes] [bit] NULL ,
	[sabeghe_teb_sozani_no] [bit] NULL ,
	[sabeghe_teb_sozani_sharh] [nvarchar] (500)    NULL ,
	[sabeghe_ambeding_yes] [bit] NULL ,
	[sabeghe_ambeding_no] [bit] NULL ,
	[sabeghe_ambeding_sharh] [nvarchar] (500)    NULL ,
	[sabeghe_amal_jarahi_yes] [bit] NULL ,
	[sabeghe_amal_jarahi_no] [bit] NULL ,
	[sabeghe_amal_jarahi_sharh] [nvarchar] (500)    NULL ,
	[sabeghe_masraf_daro_yes] [bit] NULL ,
	[sabeghe_masraf_daro_no] [bit] NULL ,
	[sabeghe_masraf_daro_sharh] [nvarchar] (500)    NULL ,
	[sabeghe_rezhim_yes] [bit] NULL ,
	[sabeghe_rezhim_no] [bit] NULL ,
	[mizan_faliat_rozaneh_manzel] [bit] NULL ,
	[mizan_faliat_rozaneh_shoghli] [bit] NULL ,
	[mizan_faliat_piadeh_ravi_rozaneh] [bit] NULL ,
	[mizan_faliat_varzesh_dar_bashgah] [bit] NULL ,
	[mizan_masraf_chay] [bit] NULL ,
	[mizan_masraf_gahveh] [bit] NULL ,
	[mizan_masraf_noshidani_sayer] [bit] NULL ,
	[mizan_masraf_noshidani_sharh] [nvarchar] (500)    NULL ,
	[mizan_masraf_tanagholat_chips] [bit] NULL ,
	[mizan_masraf_tanagholat_shokolat] [bit] NULL ,
	[mizan_masraf_tanagholat_bastani] [bit] NULL ,
	[mizan_masraf_tanagholat_sayer] [bit] NULL ,
	[mizan_masraf_tanagholat_sharh] [nvarchar] (500)    NULL ,
	[bishtarin_masraf_fast_food] [bit] NULL ,
	[bishtarin_masraf_amadeh_restoran] [bit] NULL ,
	[bishtarin_masraf_berenj_nan] [bit] NULL ,
	[bishtarin_masraf_makaroni] [bit] NULL ,
	[bishtarin_masraf_miveh_sabzi] [bit] NULL ,
	[mizan_masraf_ab_livan] [int] NULL ,
	[hazf_vadeh_sobhane] [bit] NULL ,
	[hazf_vadeh_nahar] [bit] NULL ,
	[hazf_vadeh_sham] [bit] NULL ,
	[hazf_vadeh_mian_vadeh_ghabl_zohr] [bit] NULL ,
	[hazf_vadeh_asraneh] [bit] NULL ,
	[hazf_vadeh_hichkodam] [bit] NULL ,
	[masraf_mavad_sorkh_2_dar_hafteh] [bit] NULL ,
	[masraf_mavad_sorkh_3_dar_hafteh] [bit] NULL ,
	[masraf_mavad_sorkh_bish_3_dar_hafteh] [bit] NULL ,
	[masraf_mavad_sorkh_sharh] [nvarchar] (500)    NULL ,
	[code_user_insert] [int] NULL ,
	[insert_time] [datetime] NULL ,
	[code_user_edit] [int] NULL ,
	[edit_time] [datetime] NULL ,
	[code_shift] [int] NULL ,
	[code_shobeh] [int] NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Examination] WITH NOCHECK ADD 
	CONSTRAINT [PK_checkup] PRIMARY KEY  CLUSTERED 
	(
		[id]
	)  ON [PRIMARY] 
GO

ALTER TABLE [dbo].[ExaminationDetail] WITH NOCHECK ADD 
	CONSTRAINT [PK_ExaminationDetail] PRIMARY KEY  CLUSTERED 
	(
		[id]
	)  ON [PRIMARY] 
GO

-- 1398/02/22


ALTER TABLE [dbo].[Examination]
   add [doremoch] [float] NULL
Go


ALTER TABLE [dbo].[ExaminationDetail]
   add [sabeghe_alerzhi_sharh] [nvarchar] (500)    NULL
Go


ALTER TABLE [dbo].[ExaminationDetail]
   add [bishtarin_masraf_sharh] [nvarchar] (500)    NULL
Go


ALTER TABLE [dbo].[ExaminationDetail]
   add [mizan_masraf_tanagholat_maghzijat] [bit] NULL 
Go

ALTER TABLE [dbo].[ExaminationDetail]
   add [bishtarin_masraf_proteinha] [bit] NULL 
Go


ALTER TABLE [dbo].[users]
   add [ab_del_bimar] [bit] NULL 
Go


-- 1398/03/04


ALTER TABLE [dbo].[darmanha_select]
   add [UR] [char] (20) NULL 
 Go
 ALTER TABLE [dbo].[darmanha_select]
   add [UL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[darmanha_select]
   add [LL] [char] (20) NULL 
 Go
  ALTER TABLE [dbo].[darmanha_select]
   add [LR] [char] (20) NULL 
 Go

--1398/04/01

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_change_code_bimar_for_tables' AND type = 'P')
   DROP PROCEDURE sp_change_code_bimar_for_tables
GO


create PROCEDURE [dbo].[sp_change_code_bimar_for_tables](@from_code int,@to_code int)

AS
BEGIN

declare @Cnt int



    select @Cnt=count(*) from bimaran where code_bimar=@to_code

	if @Cnt=0 
	begin

	update bimaran  set code_bimar=@to_code
       where code_bimar= @from_code

	update vaght_dehi  set code_bimar=@to_code
       where code_bimar= @from_code

	update morajeat  set code_bimar=@to_code
       where code_bimar= @from_code

	update bimaran_aks_person  set code_bimar=@to_code
       where code_bimar= @from_code

	update Bimaran_Image  set code_bimar=@to_code
       where code_bimar= @from_code

	update Auto_SMS  set code_bimar=@to_code
       where code_bimar= @from_code

	update labratvar  set code_bimar=@to_code
       where code_bimar= @from_code


	   end;

END

Go
-- exec sp_change_code_bimar_for_tables 10 , 20

ALTER TABLE [dbo].[settingc]
   add [max_or_min_code_bimar]  [bit] NULL
Go
 update settingc set max_or_min_code_bimar=1 where max_or_min_code_bimar is  null
Go
--  jahat code_manfi
-- update settingc set max_or_min_code_bimar=0
Go
ALTER TABLE [dbo].[Variz_Be_Hesab_Banki]
   add [code_morajeh] [int] NULL
Go

ALTER TABLE [dbo].[users]
   add [ab_edit_bimar_manfi] [bit] NULL 

Go
update users set ab_edit_bimar_manfi=1 where ab_edit_bimar_manfi is null
Go

--1398/04/02
ALTER TABLE [dbo].[Cheque]
   add [code_morajeh] [int] NULL
Go

ALTER TABLE [dbo].[Cheque]
   add [code_morajeh] [int] NULL
Go

--1398/04/05

ALTER TABLE [dbo].[settingc]
   add [Tabrik_Tashkil_Parvandeh_text_code_manfi]  [nvarchar] (500)
Go
update settingc set Tabrik_Tashkil_Parvandeh_text_code_manfi=' حضور شما را در این مرکز تبریک میگوئیم  . نید سافت '
 where Tabrik_Tashkil_Parvandeh_text_code_manfi is null
Go
-- update settingc set Tabrik_Tashkil_Parvandeh_text_code_manfi='  Tabrik_Tashkil_Parvandeh_text_code_manfi  :)  NeedSoft'
Go

--1398/04/11

ALTER TABLE [dbo].[pay]
   add [active] [bit] NULL
Go
update pay set active=1 where  (Code_Pay < 5 ) and   (active is null) 
Go
update pay set active=0 where  (Code_Pay >= 5 ) and   (active is null) 
Go

ALTER TABLE [dbo].[settingc]
   add [elzam_sh_bimeh] [bit] NULL
Go
update settingc set elzam_sh_bimeh=0 where elzam_sh_bimeh is null
Go
-- elzam_sh_bimeh where code_bimah <> 1 or code_bimah<> 10
-- update settingc set elzam_sh_bimeh=1 
Go

--1398/04/12
ALTER TABLE [dbo].[vaght_dehi]
   add [entezar] [bit] NULL 
Go
update vaght_dehi set entezar=0 where entezar is null
Go
ALTER TABLE [dbo].[vaght_dehi]
   add [canceli] [bit] NULL 
Go
update vaght_dehi set canceli=0 where canceli is null
Go

--1398/04/16

ALTER TABLE [dbo].[settingc]
   add [elzam_tarikh_saghf_bimeh] [bit] NULL
Go
update settingc set elzam_tarikh_saghf_bimeh=0 where elzam_tarikh_saghf_bimeh is null
Go
-- update settingc set elzam_sh_bimeh=1 
-- update settingc set elzam_tarikh_saghf_bimeh=0
Go

--1398/04/22
ALTER TABLE [dbo].[users]
   add [ab_odati] [bit] NULL 

Go
update users set ab_odati=0 where ab_odati is null
Go

-- 1398/04/25

Go

--1398/04/22
ALTER TABLE [dbo].[bimaran]
   add [unid] [varchar] (15) NULL
Go



DROP VIEW [dbo].[update_sh_kargozini]
Go
CREATE VIEW [dbo].[update_sh_kargozini]
AS
SELECT        dbo.morajeat.code_morajeh, dbo.morajeat.code_bimar, dbo.morajeat.sh_kargozini, dbo.bimaran.sh_kargozini AS sh_kargozini_new
FROM            dbo.morajeat INNER JOIN
                         dbo.bimaran ON dbo.morajeat.code_bimar = dbo.bimaran.code_bimar

GO
-- update update_sh_kargozini set sh_kargozini=sh_kargozini_new

  --1398/05/06

CREATE TABLE [dbo].[SP_Daynamic_Report](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[report_name] [nvarchar](500) NOT NULL,
	[sp_name] [nvarchar](100) NOT NULL,
	[fr_name] [nvarchar](500) NOT NULL,
	[active] [bit] NOT NULL,
	[sp_parameters] [nvarchar](100) NULL,
	[rw] [int] NULL,
 CONSTRAINT [PK_SP_Daynamic_Report] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SP_Daynamic_Report]
    add [code_system] int Null
Go
update SP_Daynamic_Report set code_system=1 where code_system is Null
Go

-- فقط sql2014

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_sum_pezeshkan_1_old' AND type = 'P')
   DROP PROCEDURE sp_report_sum_pezeshkan_1_old
GO

create PROCEDURE [dbo].[sp_report_sum_pezeshkan_1_old]
AS
BEGIN
      select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed
	  from morajeat m group by code_pezeshk
END

Go



IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = '_sp_bimeh_sarjam_pardakhti')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N' گزارش نمونه سرجمع پزشکان  ', 'sp_report_sum_pezeshkan_1', 'sp_report_sum_pezeshkan_1.fr3', 1, 'sp_parameters', 1,1)

END

GO



IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = '_sp_bimeh_sarjam_pardakhti')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N' گزارش سرجمع پرداختی بیمه ها  ', '_sp_bimeh_sarjam_pardakhti', '_sp_bimeh_sarjam_pardakhti.fr3', 1, 'sp_parameters', 2,1)

END

GO


IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_report_with_para_2_')
BEGIN
INSERT INTO SP_Daynamic_Report
           (report_name
           ,sp_name
           ,fr_name
           ,active
           ,sp_parameters
           ,rw
		   ,code_system)
     VALUES
           (N' گزارش نمونه 2  '
           ,'sp_report_with_para_2_'
           ,'sp_report_with_para_2_.fr3'
           ,1
           ,'sp_parameters'
           ,2,1)

END

Go



IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_search_all_tables_field_value' AND type = 'P')
   DROP PROCEDURE sp_search_all_tables_field_value
Go
Create PROCEDURE [dbo].[sp_search_all_tables_field_value]
(
@SearchStr nvarchar(100)
)
AS
BEGIN


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results
 END

--  Search for one value in any column of any table inside a database
--  exec sp_search_all_tables_field_value  'معرف'
Go


IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_search_all_tables_field_name' AND type = 'P')
   DROP PROCEDURE sp_search_all_tables_field_name
Go

Create PROCEDURE [dbo].[sp_search_all_tables_field_name]
(
@field_name nvarchar(100),
@field_type nvarchar(100),
@table_name nvarchar(100)
)
AS
set @field_name=ltrim(rtrim(@field_name));
set @field_type=ltrim(rtrim(@field_type));
set @table_name=ltrim(rtrim(@table_name));
if (len(@field_name)> 0)
BEGIN  
DECLARE @mywhere nvarchar(1000);
DECLARE @mystmt nvarchar(1000);

   set @mystmt=' SELECT TABLE_NAME, COLUMN_NAME ,DATA_TYPE FROM information_schema.columns  where 1>0 '
   set  @mywhere=' and  column_name like '''+ '%'+ @field_name + '%'+''''

   if (len(@field_type)> 0)
   set  @mywhere=@mywhere+' and  data_type = '''+ @field_type +''''

      if (len(@table_name)> 0)
   set  @mywhere=@mywhere+' and  table_name like = '''+ '%'+ @table_name + '%'+''''


   set @mystmt= @mystmt+@mywhere

   --select @mystmt

   exec (@mystmt)

END

 -- 1398/05/09 Ali chamani
 -- exec sp_search_all_tables_field_name 'show','',''

/*




   /*
     -- for loop and action
   		DECLARE cursor_select_auto_sms CURSOR FAST_FORWARD
		FOR SELECT TOP 10  id,SMS_MSG, SMS_Mobile FROM Auto_SMS 
			WHERE @tarikh BETWEEN sdate AND edate 
				AND @saat BETWEEN stime AND etime 
				AND code_babat = @code_babat
				AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))
			ORDER BY id DESC

		OPEN cursor_select_auto_sms
		FETCH NEXT FROM cursor_select_auto_sms INTO @id_auto, @sms_msg, @sms_mobile

		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC api_asanak_send_sms_proc @username, @password, @source, @sms_msg ,@sms_mobile, @id_auto 
		
			FETCH NEXT FROM cursor_select_auto_sms INTO @id_auto, @sms_msg, @sms_mobile
		END

		CLOSE cursor_select_auto_sms
		DEALLOCATE cursor_select_auto_sms

		*/








     set @mywhere=' where del=0 Order by cp '
     set @mystmt =' SELECT top 100 cp,np,nid,unid,eid,mobil,tel,fax,email,sdate,edate,bdate,web,addr1,pocd1 FROM per '
     set @mystmt=@mystmt+@mywhere
     exec (@mystmt) 

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
table_name like 'setting%'   and 
column_name like '%show%'

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
table_name like 'setting%'   and 
column_name like '%sms%' 

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
table_name like 'setting%'   and 
column_name like '%moaref%'


SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
column_name like '%moaref%'


SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
column_name like '%code_ertebat%'


*/



Go
--------------
/*
update bimaran 
set bedehi=(select SUM(r_bed - r_bes) from morajeat where code_bimar=bimaran.code_bimar)
,bedehi_roz=(select SUM(r_bed - r_bes) from morajeat where code_bimar=bimaran.code_bimar)
-(select SUM(r_bed - r_bes) from morajeat where code_bimar=bimaran.code_bimar and tarikh <'1397/11/10' )
 where code_bimar in (select code_bimar from morajeat where tarikh > '1397/11/10'  group by code_bimar )
*/

--  ALTER TABLE [dbo].[morajeat_filter]
--   add [bedehi_roz_bimaran] [nvarchar](1000) NULL
--  Go
Go

--  1398/05/08
ALTER TABLE [dbo].[users]
   add [ab_mohasebe_porsant] [bit] NULL 

Go
update users set ab_mohasebe_porsant=0 where ab_mohasebe_porsant is null
Go
-- 1398/05/15

DROP VIEW [dbo].[View_Bimeh_Sarjam_Period]
Go
CREATE VIEW [dbo].[View_Bimeh_Sarjam_Period]
AS
SELECT        dbo.morajeat.code_bimar, dbo.morajeat.tarikh, dbo.bimaran.code_bimeh, dbo.morajeat.r_bimeh, dbo.bimaran.sh_bimeh, dbo.bimaran.sh_kargozini, 
                         dbo.bimaran.code_meli, dbo.bimaran.unid
FROM            dbo.morajeat INNER JOIN
                         dbo.bimaran ON dbo.morajeat.code_bimar = dbo.bimaran.code_bimar

GO



ALTER TABLE [dbo].[settingc]
   add [elzam_shomare_dandan_paziresh] [bit] NULL
Go
update settingc set elzam_shomare_dandan_paziresh=0 where elzam_shomare_dandan_paziresh is null
Go
-- update settingc set elzam_shomare_dandan_paziresh=1 
-- update settingc set elzam_shomare_dandan_paziresh=0
Go



-- ab_code_movaghat_to_daem
--ab_code_daem_to_movaghat

ALTER TABLE [dbo].[users]
   add [ab_code_movaghat_to_daem] [bit] NULL 
Go
update users set ab_code_movaghat_to_daem=1 where ab_code_movaghat_to_daem is null
Go

ALTER TABLE [dbo].[users]
   add [ab_code_daem_to_movaghat] [bit] NULL 
Go
update users set ab_code_daem_to_movaghat=1 where ab_code_daem_to_movaghat is null
Go

-- 1398/05/16

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_with_para_1_' AND type = 'P')
   DROP PROCEDURE sp_report_with_para_1_
Go

create PROCEDURE [dbo].[sp_report_with_para_1_](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    set @mystmt='select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

  
    if(LEN(@code_bakhsh)>0) 
    set @mywhere =@mywhere+' and code_bakhsh='+@code_bakhsh


     if(LEN(@code_pezeshk)>0) 
   set @mywhere =@mywhere+' and code_pezeshk='+@code_pezeshk

       if(LEN(@code_darman)>0) 
   set @mywhere =@mywhere+' and code_darman='+@code_darman


       if(LEN(@code_shift)>0) 
   set @mywhere =@mywhere+' and code_shift='+@code_shift


       if(LEN(@code_user_insert)>0) 
   set @mywhere =@mywhere+' and code_user_insert='+@code_user_insert


       if(LEN(@code_pay)>0) 
   set @mywhere =@mywhere+' and code_pay='+@code_pay


       if(LEN(@code_shobeh)>0) 
   set @mywhere =@mywhere+' and code_shobeh='+@code_shobeh



   if(LEN(@from_time)>0) and (LEN(@to_time)>0) 
   set @mywhere =@mywhere+' and insert_time between '''+@from_time+''''+' and '+''''+@to_time+''''


   if(LEN(@sh_kargozini)>0) 
   set @mywhere =@mywhere+' and sh_kargozini='''+@sh_kargozini+''''


    if(LEN(@code_ertebat)>0) 
   set @mywhere =@mywhere+' and code_ertebat='''+@code_ertebat+''''

   if(LEN(@code_shift_str)>0) 
   set @mywhere =@mywhere+@code_shift_str


   if(LEN(@code_bimeh_str)>0) 
   set @mywhere =@mywhere+@code_bimeh_str


   if(LEN(@code_bakhsh_str)>0) 
   set @mywhere =@mywhere+@code_bakhsh_str



   if(LEN(@code_pezeshk_str)>0) 
   set @mywhere =@mywhere+@code_pezeshk_str


   if(LEN(@code_yaraneh)>0) 
   set @mywhere =@mywhere+' and code_yaraneh='+@code_yaraneh



   if(LEN(@code_mokammel)>0) 
   set @mywhere =@mywhere+' and code_mokammel='+@code_mokammel


    if(LEN(@code_dastyar)>0) 
   set @mywhere =@mywhere+' and code_dastyar='+@code_dastyar

    
 
   set @mygroup=' group by code_pezeshk '
  
   set @myorder=' order by code_pezeshk '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

   -- select @mystmt

   exec (@mystmt)



END
-- 1398/05/16 by ali chamani
-- exec sp_report_with_para_1_ '1397/01/01','1398/20/20','','','','','','','','','','','','','','','','','','','',''


/*

     select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed
	  from morajeat m group by code_pezeshk


*/


/*

DECLARE @mywhere nvarchar(1000);
DECLARE @mystmt nvarchar(1000);

   set @mystmt=' SELECT TABLE_NAME, COLUMN_NAME ,DATA_TYPE  FROM information_schema.columns  where 1>0 '
   set  @mywhere=' and  column_name like '''+ '%'+ @field_name + '%'+''''

   if (len(@field_type)> 0)
   set  @mywhere=@mywhere+' and  data_type = '''+ @field_type +''''

      if (len(@table_name)> 0)
   set  @mywhere=@mywhere+' and  table_name like = '''+ '%'+ @table_name + '%'+''''


   set @mystmt= @mystmt+@mywhere

  -- select @mystmt

   exec (@mystmt)

*/



IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_sum_pezeshkan_1' AND type = 'P')
   DROP PROCEDURE sp_report_sum_pezeshkan_1
Go

create PROCEDURE [dbo].[sp_report_sum_pezeshkan_1](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    set @mystmt='select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

  
    if(LEN(@code_bakhsh)>0) 
    set @mywhere =@mywhere+' and code_bakhsh='+@code_bakhsh


     if(LEN(@code_pezeshk)>0) 
   set @mywhere =@mywhere+' and code_pezeshk='+@code_pezeshk

       if(LEN(@code_darman)>0) 
   set @mywhere =@mywhere+' and code_darman='+@code_darman


       if(LEN(@code_shift)>0) 
   set @mywhere =@mywhere+' and code_shift='+@code_shift


       if(LEN(@code_user_insert)>0) 
   set @mywhere =@mywhere+' and code_user_insert='+@code_user_insert


       if(LEN(@code_pay)>0) 
   set @mywhere =@mywhere+' and code_pay='+@code_pay


       if(LEN(@code_shobeh)>0) 
   set @mywhere =@mywhere+' and code_shobeh='+@code_shobeh



   if(LEN(@from_time)>0) and (LEN(@to_time)>0) 
   set @mywhere =@mywhere+' and insert_time between '''+@from_time+''''+' and '+''''+@to_time+''''


   if(LEN(@sh_kargozini)>0) 
   set @mywhere =@mywhere+' and sh_kargozini='''+@sh_kargozini+''''


    if(LEN(@code_ertebat)>0) 
   set @mywhere =@mywhere+' and code_ertebat='''+@code_ertebat+''''

   if(LEN(@code_shift_str)>0) 
   set @mywhere =@mywhere+@code_shift_str


   if(LEN(@code_bimeh_str)>0) 
   set @mywhere =@mywhere+@code_bimeh_str


   if(LEN(@code_bakhsh_str)>0) 
   set @mywhere =@mywhere+@code_bakhsh_str



   if(LEN(@code_pezeshk_str)>0) 
   set @mywhere =@mywhere+@code_pezeshk_str


   if(LEN(@code_yaraneh)>0) 
   set @mywhere =@mywhere+' and code_yaraneh='+@code_yaraneh



   if(LEN(@code_mokammel)>0) 
   set @mywhere =@mywhere+' and code_mokammel='+@code_mokammel


    if(LEN(@code_dastyar)>0) 
   set @mywhere =@mywhere+' and code_dastyar='+@code_dastyar

    
 
   set @mygroup=' group by code_pezeshk '
  
   set @myorder=' order by code_pezeshk '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

   -- select @mystmt

   exec (@mystmt)



END
-- 1398/05/16 by ali chamani
-- exec sp_report_with_para_1_ '1397/01/01','1398/20/20','','','','','','','','','','','','','','','','','','','',''


/*

     select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed
	  from morajeat m group by code_pezeshk


*/


/*

DECLARE @mywhere nvarchar(1000);
DECLARE @mystmt nvarchar(1000);

   set @mystmt=' SELECT TABLE_NAME, COLUMN_NAME ,DATA_TYPE  FROM information_schema.columns  where 1>0 '
   set  @mywhere=' and  column_name like '''+ '%'+ @field_name + '%'+''''

   if (len(@field_type)> 0)
   set  @mywhere=@mywhere+' and  data_type = '''+ @field_type +''''

      if (len(@table_name)> 0)
   set  @mywhere=@mywhere+' and  table_name like = '''+ '%'+ @table_name + '%'+''''


   set @mystmt= @mystmt+@mywhere

  -- select @mystmt

   exec (@mystmt)

*/






Go

---  جهت کنترل سقف بیمه 
CREATE TABLE [dbo].[bimeh_bimar](
  [code_bb] [int] IDENTITY(1,1) NOT NULL,
  [code_bimeh] [int] NOT NULL,
  [code_bimar] [int] NOT NULL,
  [tarikh_shoro] [char](10) NOT NULL,
  [tarikh_payan] [char](10) NOT NULL,
  [saghf_bimeh] [money] NULL,
  [saghf_khanevadeh] [bit] NULL,
 CONSTRAINT [PK_bimeh_bimar] PRIMARY KEY CLUSTERED 
(
  [code_bb] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO


-- 1398/06/04


--setting_a_sms

ALTER TABLE [dbo].[setting_a_sms]
    add [pishvand_vaght_emroz_txt] [nvarchar](200) NULL
  Go
  ALTER TABLE [dbo].[setting_a_sms]
    add [pishvand_vaght_farda_txt] [nvarchar](200) NULL
  Go

  update setting_a_sms set pishvand_vaght_emroz_txt=' با سلام وقت شما امروز  ' where   pishvand_vaght_emroz_txt is null
  Go
  update setting_a_sms set pishvand_vaght_farda_txt='با سلام وقت شما فردا   ' where  pishvand_vaght_farda_txt is null
  Go



  CREATE TABLE [dbo].[bimeh_bimar_pardakhti](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[code_bb] [int] NOT NULL,
	[pardakhti_bimeh] [money] NOT NULL,
	[pardakhti_tarikh] [char](10) NOT NULL,
 CONSTRAINT [PK_bimeh_bimar_pardakhti] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[bimeh_bimar]
   DROP COLUMN  [pardakhti_bimeh] 
  Go
Go

 ALTER TABLE [dbo].[bimeh_bimar]
   DROP COLUMN  [pardakhti_tarikh] 
  Go


IF EXISTS (SELECT name FROM sysobjects
      WHERE name = '_sp_bimeh_bimar_sarjam' AND type = 'P')
   DROP PROCEDURE _sp_bimeh_bimar_sarjam
   
Go
  

create PROCEDURE [dbo].[_sp_bimeh_bimar_sarjam](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10)
)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    set @mystmt='select code_bimeh,(select name_bimeh from bimeha where code_bimeh=m.code_bimeh) as name_bimeh,sum(r_bimeh) as s_r_bimeh
	    from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

 
   set @mygroup=' group by code_bimeh '
  
   set @myorder=' order by code_bimeh '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

 
   -- select @mystmt

   exec (@mystmt)



END
-- 1398/06/02 by ali chamani
-- exec sp_bimeh_bimar_sarjam_ '1391/01/01','1398/20/20','',''


/*

     select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed
	  from morajeat m group by code_pezeshk


*/


/*

DECLARE @mywhere nvarchar(1000);
DECLARE @mystmt nvarchar(1000);

   set @mystmt=' SELECT TABLE_NAME, COLUMN_NAME ,DATA_TYPE  FROM information_schema.columns  where 1>0 '
   set  @mywhere=' and  column_name like '''+ '%'+ @field_name + '%'+''''

   if (len(@field_type)> 0)
   set  @mywhere=@mywhere+' and  data_type = '''+ @field_type +''''

      if (len(@table_name)> 0)
   set  @mywhere=@mywhere+' and  table_name like = '''+ '%'+ @table_name + '%'+''''


   set @mystmt= @mystmt+@mywhere

  -- select @mystmt

   exec (@mystmt)

*/

/*
IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_sum_pezeshkan_1' AND type = 'P')
   DROP PROCEDURE sp_report_sum_pezeshkan_1
   */



Go
ALTER TABLE [dbo].[users]
   add [ab_edit_r_pezeshk] [bit] NULL 

Go


-- 1398/06/14
ALTER TABLE [dbo].[morajeat]
   add [code_ranandeh] [int] NULL 

Go

CREATE TABLE [dbo].[ranandeh](
	[code_ranandeh] [int] NOT NULL,
	[name_ranandeh] [nvarchar](200) NOT NULL,
	[active] [bit] NULL,
 CONSTRAINT [PK_ranandeh] PRIMARY KEY CLUSTERED 
(
	[code_ranandeh] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO


Go
insert ranandeh (code_ranandeh,name_ranandeh,active) values ('0',' راننده با ماشینش','1')
Go
insert ranandeh (code_ranandeh,name_ranandeh,active) values ('1','انتخاب راننده با ماشین حرفه ای','1')
Go

ALTER TABLE [dbo].[settingc]
    add [code_ranandeh] [int] NULL 
Go


IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_with_para_2_' AND type = 'P')
   DROP PROCEDURE sp_report_with_para_2_

   Go

create PROCEDURE [dbo].[sp_report_with_para_2_](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));
set @code_ranandeh=LTRIM(RTRIM(@code_ranandeh));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    set @mystmt='select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

  
    if(LEN(@code_bakhsh)>0) 
    set @mywhere =@mywhere+' and code_bakhsh='+@code_bakhsh


     if(LEN(@code_pezeshk)>0) 
   set @mywhere =@mywhere+' and code_pezeshk='+@code_pezeshk

       if(LEN(@code_darman)>0) 
   set @mywhere =@mywhere+' and code_darman='+@code_darman


       if(LEN(@code_shift)>0) 
   set @mywhere =@mywhere+' and code_shift='+@code_shift


       if(LEN(@code_user_insert)>0) 
   set @mywhere =@mywhere+' and code_user_insert='+@code_user_insert


       if(LEN(@code_pay)>0) 
   set @mywhere =@mywhere+' and code_pay='+@code_pay


       if(LEN(@code_shobeh)>0) 
   set @mywhere =@mywhere+' and code_shobeh='+@code_shobeh



   if(LEN(@from_time)>0) and (LEN(@to_time)>0) 
   set @mywhere =@mywhere+' and insert_time between '''+@from_time+''''+' and '+''''+@to_time+''''


   if(LEN(@sh_kargozini)>0) 
   set @mywhere =@mywhere+' and sh_kargozini='''+@sh_kargozini+''''


    if(LEN(@code_ertebat)>0) 
   set @mywhere =@mywhere+' and code_ertebat='''+@code_ertebat+''''

   if(LEN(@code_shift_str)>0) 
   set @mywhere =@mywhere+@code_shift_str


   if(LEN(@code_bimeh_str)>0) 
   set @mywhere =@mywhere+@code_bimeh_str


   if(LEN(@code_bakhsh_str)>0) 
   set @mywhere =@mywhere+@code_bakhsh_str



   if(LEN(@code_pezeshk_str)>0) 
   set @mywhere =@mywhere+@code_pezeshk_str


   if(LEN(@code_yaraneh)>0) 
   set @mywhere =@mywhere+' and code_yaraneh='+@code_yaraneh



   if(LEN(@code_mokammel)>0) 
   set @mywhere =@mywhere+' and code_mokammel='+@code_mokammel


    if(LEN(@code_dastyar)>0) 
   set @mywhere =@mywhere+' and code_dastyar='+@code_dastyar


   if(LEN(@code_ranandeh)>0) 
   set @mywhere =@mywhere+' and code_ranandeh='+@code_ranandeh

    
 
   set @mygroup=' group by code_pezeshk '
  
   set @myorder=' order by code_pezeshk '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

   -- select @mystmt

   exec (@mystmt)



END

GO
-- 1398/06/14 by ali chamani
-- exec sp_report_with_para_2_ '1397/01/01','1398/20/20','','','','','','','','','','','','','','','','','','','','',''

/*


IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_sum_pezeshkan_1' AND type = 'P')
   DROP PROCEDURE sp_report_sum_pezeshkan_1

   */


IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_sum_pezeshkan_1' AND type = 'P')
   DROP PROCEDURE sp_report_sum_pezeshkan_1
   

Create PROCEDURE [dbo].[sp_report_sum_pezeshkan_1](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	


)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));
set @code_ranandeh=LTRIM(RTRIM(@code_ranandeh));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    set @mystmt='select code_pezeshk,
	  (select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk, 
	  sum(r_bed) as s_r_bed from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

  
    if(LEN(@code_bakhsh)>0) 
    set @mywhere =@mywhere+' and code_bakhsh='+@code_bakhsh


     if(LEN(@code_pezeshk)>0) 
   set @mywhere =@mywhere+' and code_pezeshk='+@code_pezeshk

       if(LEN(@code_darman)>0) 
   set @mywhere =@mywhere+' and code_darman='+@code_darman


       if(LEN(@code_shift)>0) 
   set @mywhere =@mywhere+' and code_shift='+@code_shift


       if(LEN(@code_user_insert)>0) 
   set @mywhere =@mywhere+' and code_user_insert='+@code_user_insert


       if(LEN(@code_pay)>0) 
   set @mywhere =@mywhere+' and code_pay='+@code_pay


       if(LEN(@code_shobeh)>0) 
   set @mywhere =@mywhere+' and code_shobeh='+@code_shobeh



   if(LEN(@from_time)>0) and (LEN(@to_time)>0) 
   set @mywhere =@mywhere+' and insert_time between '''+@from_time+''''+' and '+''''+@to_time+''''


   if(LEN(@sh_kargozini)>0) 
   set @mywhere =@mywhere+' and sh_kargozini='''+@sh_kargozini+''''


    if(LEN(@code_ertebat)>0) 
   set @mywhere =@mywhere+' and code_ertebat='''+@code_ertebat+''''

   if(LEN(@code_shift_str)>0) 
   set @mywhere =@mywhere+@code_shift_str


   if(LEN(@code_bimeh_str)>0) 
   set @mywhere =@mywhere+@code_bimeh_str


   if(LEN(@code_bakhsh_str)>0) 
   set @mywhere =@mywhere+@code_bakhsh_str



   if(LEN(@code_pezeshk_str)>0) 
   set @mywhere =@mywhere+@code_pezeshk_str


   if(LEN(@code_yaraneh)>0) 
   set @mywhere =@mywhere+' and code_yaraneh='+@code_yaraneh



   if(LEN(@code_mokammel)>0) 
   set @mywhere =@mywhere+' and code_mokammel='+@code_mokammel


    if(LEN(@code_dastyar)>0) 
   set @mywhere =@mywhere+' and code_dastyar='+@code_dastyar


    if(LEN(@code_ranandeh)>0) 
   set @mywhere =@mywhere+' and code_ranandeh='+@code_ranandeh

    
 
   set @mygroup=' group by code_pezeshk '
  
   set @myorder=' order by code_pezeshk '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

   -- select @mystmt

   exec (@mystmt)



END
Go
-- 1398/06/14 by ali chamani
-- exec sp_report_sum_pezeshkan_1 '1397/01/01','1398/20/20','','','','','','','','','','','','','','','','','','','','',''

  
create PROCEDURE [dbo].[_sp_bimeh_sarjam_pardakhti](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	
)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    if ((LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) and (LEN(@code_bimeh)>0)) 
	begin

    set @mystmt='select code_bimar,
	(select name +'+' '+'+ famil from bimaran where code_bimar=m.code_bimar) as name_bimar,
	sum(r_bimeh) as s_r_bimeh,
	(select sum(pardakhti_bimeh) from View_bimeh_bimar_pardakhti 
	where '''+@from_tarikh+''' between tarikh_shoro and tarikh_payan and '''+
	@to_tarikh+''' between tarikh_shoro and tarikh_payan and '
	+  'code_bimeh='+@code_bimeh+' and code_bimar=m.code_bimar  ) as s_pardakhti_bimeh
	    from morajeat m '


	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh


   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar



 
   set @mygroup=' group by code_bimar '
  
   set @myorder=' order by code_bimar '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

 
   -- select @mystmt

   exec (@mystmt)
   end;


END


-- 1398/06/15 by ali chamani
-- exec _sp_bimeh_sarjam_pardakhti '1391/01/01','1398/20/20','','1','','','','','','','','','','','','','','','','','','',''

Go


DROP VIEW [dbo].[[View_bimeh_bimar_pardakhti]
Go

CREATE VIEW [dbo].[View_bimeh_bimar_pardakhti]
AS
SELECT        dbo.bimeh_bimar.code_bimeh, dbo.bimeh_bimar.code_bimar, dbo.bimeh_bimar.tarikh_shoro, dbo.bimeh_bimar.tarikh_payan, dbo.bimeh_bimar.saghf_bimeh, 
                         dbo.bimeh_bimar.saghf_khanevadeh, dbo.bimeh_bimar_pardakhti.pardakhti_bimeh, dbo.bimeh_bimar_pardakhti.pardakhti_tarikh
FROM            dbo.bimeh_bimar INNER JOIN
                         dbo.bimeh_bimar_pardakhti ON dbo.bimeh_bimar.code_bb = dbo.bimeh_bimar_pardakhti.code_bb

GO



-- 1398/06/22 by ali chamani

ALTER TABLE [dbo].[settingc]
    add [adam_sabte_paziresh_after_not_finished_ted] [int] NULL 
  Go
  update settingc set adam_sabte_paziresh_after_not_finished_ted=0 where adam_sabte_paziresh_after_not_finished_ted is null
  Go
 -- update settingc set adam_sabte_paziresh_after_not_finished_ted=2
 -- Update settingb set show_Not_Finished=1
  Go

ALTER TABLE [dbo].[bimeha]
    add [check_saghf_on_paziresh] [bit] NULL
  Go
  update bimeha set check_saghf_on_paziresh=0 where check_saghf_on_paziresh is null
  Go




IF EXISTS (SELECT name FROM sysobjects
      WHERE name = '_sp_bimeh_bimar_list_khanevadeh' AND type = 'P')
   DROP PROCEDURE _sp_bimeh_bimar_list_khanevadeh
 Go
Create PROCEDURE [dbo].[_sp_bimeh_bimar_list_khanevadeh](
-- 1398/06/24 by Ali Chamani NeedSoft
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@tarikh_roz  char(10),
@sum_r_bimeh  money OUTPUT,
@unid  char(10) OUTPUT,
@message varchar(500) OUTPUT
)
AS

set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @tarikh_roz=LTRIM(RTRIM(@tarikh_roz));

set @sum_r_bimeh=0;
set @unid='';
set @message='';

declare @code_meli_sarparsat char(10);
declare @code_meli char(10);


BEGIN

      select @code_meli_sarparsat=LTRIM(RTRIM(unid)),@code_meli=LTRIM(RTRIM(code_meli)) from bimaran where code_bimar=@code_bimar
	  if (@code_meli_sarparsat<>@code_meli)
	  BEGIN
	       select @code_bimar=code_bimar from bimaran 
		   where code_meli=(select unid from bimaran where code_bimar=@code_bimar)
	  END;

      if ((LEN(@tarikh_roz)>0) and (LEN(@code_bimar)>0) and (LEN(@code_bimeh)>0))
	  BEGIN 
        			 select @unid=unid from bimaran where code_bimar=@code_bimar
			         set @unid=LTRIM(RTRIM(@unid));

					 if (LEN(@unid)>0)
			         BEGIN
	      
	                      select code_morajeh,tarikh,code_bimar,
						  (select name+' '+famil+' - '+code_meli from bimaran where code_bimar=m.code_bimar) as name,
						  (select name_darman from darmanha where code_darman=m.code_darman) as darman,
						  r_bimeh
			              from morajeat m 
			              where code_bimeh=@code_bimeh and r_bimeh > 0
			              and code_bimar IN (select code_bimar from bimaran where unid=@unid)
						  order by tarikh,code_morajeh

			             -- and tarikh BETWEEN @tarikh_shoro AND @tarikh_payan 

						
						  select @sum_r_bimeh=sum(r_bimeh) 
			              from morajeat  
			              where code_bimeh=@code_bimeh and r_bimeh > 0
			              and code_bimar IN (select code_bimar from bimaran where unid=@unid)
			             -- and tarikh BETWEEN @tarikh_shoro AND @tarikh_payan 
			         END
					 ELSE
					 BEGIN
	     		          SET @message=@message+' کد ملی  سرپرست مشخص نمیباشد  ';
                          set @unid='';  

	                      select code_morajeh,tarikh,code_bimar,
						  (select name+' '+famil+' - '+code_meli from bimaran where code_bimar=m.code_bimar) as name,
						  (select name_darman from darmanha where code_darman=m.code_darman) as darman,
						  r_bimeh
			              from morajeat m 
			              where code_bimeh=@code_bimeh and r_bimeh > 0
			              and code_bimar=@code_bimar
						  order by tarikh,code_morajeh

			             -- and tarikh BETWEEN @tarikh_shoro AND @tarikh_payan 

						
						  select @sum_r_bimeh=sum(r_bimeh) 
			              from morajeat  
			              where code_bimeh=@code_bimeh and r_bimeh > 0
			              and code_bimar=@code_bimar
			             -- and tarikh BETWEEN @tarikh_shoro AND @tarikh_payan 

					 END
     END
	 ELSE
	 BEGIN 
	 set @message=@message+'   فرد , بیمه و تاریخ خالی میباشد    ';

	 END;

END;

-- 1398/06/24 by Ali Chamani NeedSoft
-- EXEC
/*

DECLARE @unid char(10) ;
DECLARE @message varchar(200) ;
DECLARE @sum_r_bimeh money ;

exec _sp_bimeh_bimar_list_khanevadeh

    @code_bimar = '29126',
	@code_bimeh = '2',
	@tarikh_roz = '1398/06/01',
	
	@sum_r_bimeh=@sum_r_bimeh OUTPUT, 
    @unid =@unid OUTPUT,
    @message= @message OUTPUT;
	
	select
	    '  @sum_r_bimeh='+LTRIM(STR(@sum_r_bimeh))+CHAR(13)+ 
        '  @unid='+LTRIM(@unid)+CHAR(13)+ 
        '  @message='+LTRIM(@message) 

*/
Go

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = '_sp_bimeh_bimar_sarjam' AND type = 'P')
   DROP PROCEDURE _sp_bimeh_bimar_sarjam
Go

Create PROCEDURE [dbo].[_sp_bimeh_bimar_sarjam](
-- 1398/06/24 by Ali Chamani NeedSoft
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10)
)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);
DECLARE @unid  char(10);
DECLARE @message varchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''
set @unid=''
set @message=''

declare @code_meli_sarparsat char(10);
declare @code_meli char(10);


BEGIN

    if (LEN(@code_bimar)>0) 
	  BEGIN 

      --  پیدا کردن کدبیمار سرپرست
      select @code_meli_sarparsat=LTRIM(RTRIM(unid)),@code_meli=LTRIM(RTRIM(code_meli)) from bimaran where code_bimar=@code_bimar
	  if (@code_meli_sarparsat<>@code_meli)
	  BEGIN
	       select @code_bimar=code_bimar from bimaran 
		   where code_meli=(select unid from bimaran where code_bimar=@code_bimar)
	  END;

	  --  پیدا کردن کدملی سرپرست
	  select @unid=unid from bimaran where code_bimar=@code_bimar
	  set @unid=LTRIM(RTRIM(@unid));


    set @mystmt='select code_bimeh,
	 (select name_bimeh from bimeha where code_bimeh=m.code_bimeh) as name_bimeh,sum(r_bimeh) as s_r_bimeh
	    from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) and (LEN(@unid)>0) 
   set @mywhere =@mywhere+'and code_bimar IN (select code_bimar from bimaran where unid='''+@unid+''') '
   -- and code_bimar IN (select code_bimar from bimaran where unid=@unid)
   else
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

 
   set @mygroup=' group by code_bimeh '
  
   set @myorder=' order by code_bimeh '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

 
  -- select @mystmt

   exec (@mystmt)
   END
   ELSE
   SET @message= @message+'  کد بیمار مشخص نمیباشد '

END
-- 1398/06/24 by Ali Chamani NeedSoft
-- exec _sp_bimeh_bimar_sarjam '','','29124',''
Go
IF EXISTS (SELECT name FROM sysobjects
      WHERE name = '_sp_bimeh_bimar_sarjam_saghf_mandeh' AND type = 'P')
   DROP PROCEDURE _sp_bimeh_bimar_sarjam_saghf_mandeh
Go

create PROCEDURE [dbo].[_sp_bimeh_bimar_sarjam_saghf_mandeh](
-- 1398/06/24 by Ali Chamani NeedSoft
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@tarikh_roz  char(10),
@tarikh_shoro char(10) OUTPUT,
@tarikh_payan char(10) OUTPUT,
@saghf_khanevadeh bit OUTPUT,
@saghf_bimeh  money OUTPUT,
@sum_r_bimeh  money OUTPUT,
@saghf_mandeh  money OUTPUT,
@unid  char(10) OUTPUT,
@message varchar(500) OUTPUT
)
AS

set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @tarikh_roz=LTRIM(RTRIM(@tarikh_roz));

set @tarikh_shoro='';
set @tarikh_payan='';
set @saghf_khanevadeh=0;
set @saghf_bimeh=0;
set @sum_r_bimeh=0;
set @saghf_mandeh=0;
set @unid='';
set @message='';


declare @code_meli_sarparsat char(10);
declare @code_meli char(10);


BEGIN
      select @code_meli_sarparsat=LTRIM(RTRIM(unid)),@code_meli=LTRIM(RTRIM(code_meli)) from bimaran where code_bimar=@code_bimar
	  if (@code_meli_sarparsat<>@code_meli)
	  BEGIN
	       select @code_bimar=code_bimar from bimaran 
		   where code_meli=(select unid from bimaran where code_bimar=@code_bimar)
	  END;

  
      if ((LEN(@tarikh_roz)>0) and (LEN(@code_bimar)>0) and (LEN(@code_bimeh)>0))
	  BEGIN 

	       select top 1
	       @saghf_khanevadeh=saghf_khanevadeh,
	       @saghf_bimeh=saghf_bimeh, 
           @tarikh_shoro=tarikh_shoro,
           @tarikh_payan=tarikh_payan	  
	       from bimeh_bimar 
	       where code_bimar=@code_bimar
	       and code_bimeh=@code_bimeh
	       AND @tarikh_roz BETWEEN tarikh_shoro AND tarikh_payan  
	       order by tarikh_payan DESC 
		   
		   if (@tarikh_roz BETWEEN @tarikh_shoro AND @tarikh_payan) and (@saghf_bimeh>0)
	       BEGIN
		        
				if @saghf_khanevadeh=0 
	            BEGIN
	            
			        select @sum_r_bimeh=sum(r_bimeh) 
        			from morajeat  
		        	where code_bimar=@code_bimar
			        and code_bimeh=@code_bimeh
			        and tarikh BETWEEN @tarikh_shoro AND @tarikh_payan 

					if @sum_r_bimeh is null set @sum_r_bimeh=0
                    
					SET @saghf_mandeh=@saghf_bimeh-@sum_r_bimeh
					SET @message=@message+' سقف مانده شخص : '  +LTRIM(STR(@saghf_mandeh))

	            END
	            ELSE
	            BEGIN
	                 
					 select @unid=unid from bimaran where code_bimar=@code_bimar
			         set @unid=LTRIM(RTRIM(@unid));
					 if (LEN(@unid)>0)
			         BEGIN
					      
	                      select @sum_r_bimeh=sum(r_bimeh) 
			              from morajeat  
			              where code_bimeh=@code_bimeh
			              and code_bimar IN (select code_bimar from bimaran where unid=@unid)
			              and tarikh BETWEEN @tarikh_shoro AND @tarikh_payan 

						  if @sum_r_bimeh is null set @sum_r_bimeh=0

						  SET @saghf_mandeh=@saghf_bimeh-@sum_r_bimeh
						  SET @message=@message+' سقف مانده خانواده :'+LTRIM(STR(@saghf_mandeh))
			         END
			         ELSE
					 BEGIN
					      SET @message=@message+'- کد ملی سرپرست خالی میباشد - ';
					
                     END
             END
	     END
	     ELSE 
		 BEGIN
	     set @message=@message+' bimeh_bimar '+'  جدول  تنظیمات سقف  بیمه خارج از محدوده است   ';
	
		 END
     END
	 ELSE
	 BEGIN 
	 set @message=@message+'   فرد , بیمه و تاریخ خالی میباشد    ';

	 END;

END;

-- 1398/06/24 by Ali Chamani NeedSoft
-- EXEC
/*


DECLARE @tarikh_shoro char(10);
DECLARE @tarikh_payan char(10) ;
DECLARE @saghf_khanevadeh bit;
DECLARE @saghf_bimeh  money ;
DECLARE @sum_r_bimeh  money ;
DECLARE @saghf_mandeh  money ;
DECLARE @unid char(10) ;
DECLARE @message varchar(200) ;

exec _sp_bimeh_bimar_sarjam_saghf_mandeh

    @code_bimar = '1',
	@code_bimeh = '2',
	@tarikh_roz = '1398/06/01',
	
	@tarikh_shoro = @tarikh_shoro OUTPUT,
    @tarikh_payan = @tarikh_payan OUTPUT,
    @saghf_khanevadeh =@saghf_khanevadeh OUTPUT,
    @saghf_bimeh= @saghf_bimeh OUTPUT,
    @sum_r_bimeh = @sum_r_bimeh OUTPUT,
    @saghf_mandeh = @saghf_mandeh OUTPUT,
    @unid =@unid OUTPUT,
    @message= @message OUTPUT;
	
	select
	 	'  @tarikh_shoro='+ LTRIM(@tarikh_shoro)+CHAR(13)+ 
        '  @tarikh_payan='+LTRIM(@tarikh_payan)+CHAR(13)+ 
        '  @saghf_khanevadeh='+LTRIM(STR(@saghf_khanevadeh))+CHAR(13)+
        '  @saghf_bimeh='+LTRIM(STR(@saghf_bimeh))+CHAR(13)+ 
        '  @sum_r_bimeh='+LTRIM(STR( @sum_r_bimeh))+CHAR(13)+
        '  @saghf_mandeh='+LTRIM(STR( @saghf_mandeh))+CHAR(13)+ 
        '  @unid='+LTRIM(@unid)+CHAR(13)+ 
        '  @message='+LTRIM(@message) 


*/

Go



ALTER TABLE [dbo].[settingc]
    add [alarm_register_text] nvarchar(4000)  Null
  Go
  update settingc set alarm_register_text='  Serious error  '+char(13)+char(13)+'Access violation at address 005AE2D1 in module ''' +
      'delphipro70.bpl' + '''. Read of address 444C436A '  where alarm_register_text is null
  Go
 -- update settingc set adam_sabte_paziresh_after_not_finished_ted=2
 -- Update settingb set show_Not_Finished=1
  Go

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_with_para_3_' AND type = 'P')
   DROP PROCEDURE sp_report_with_para_3_
Go 

create PROCEDURE [dbo].[sp_report_with_para_3_](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));
set @code_ranandeh=LTRIM(RTRIM(@code_ranandeh));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN

    set @mystmt='select 
code_morajeh,
tarikh,
code_bimar,
(select famil from bimaran  where code_bimar=m.code_bimar) as name_bimar,
r_bimeh,r_bes,
(select darsad from pezeshkan where code_pezeshk=m.code_pezeshk) as darsad_pezeshk,
code_pezeshk,
(select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk,
code_darman,
(select name_darman from darmanha where code_darman=m.code_darman) as name_darman,
r_bimeh+r_bes as jame,
CASE
    WHEN (select darsad from pezeshkan where code_pezeshk=m.code_pezeshk)<=20 or
	(select darsad from pezeshkan where code_pezeshk=m.code_pezeshk) is NULL
	 THEN r_bimeh+r_bes
    ELSE (r_bimeh+r_bes)*(select darsad from pezeshkan where code_pezeshk=m.code_pezeshk)/100
END
as sahme_pezeshk,
CASE
    WHEN (select darsad from pezeshkan where code_pezeshk=m.code_pezeshk)<=20 or
	(select darsad from pezeshkan where code_pezeshk=m.code_pezeshk) is NULL
	 THEN 0
    ELSE (r_bimeh+r_bes)-((r_bimeh+r_bes)*(select darsad from pezeshkan where code_pezeshk=m.code_pezeshk)/100)
END
as sahme_clinic
from morajeat m ' 

	set @mywhere=@mywhere+' where 1> 0 ';
	
	      
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   set @mywhere =@mywhere+' and tarikh between '''+@from_tarikh+''''+' and '+''''+@to_tarikh+''''

   if(LEN(@code_bimar)>0) 
   set @mywhere =@mywhere+' and code_bimar='+@code_bimar

   if(LEN(@code_bimeh)>0) 
   set @mywhere =@mywhere+' and code_bimeh='+@code_bimeh

  
    if(LEN(@code_bakhsh)>0) 
    set @mywhere =@mywhere+' and code_bakhsh='+@code_bakhsh


     if(LEN(@code_pezeshk)>0) and (@code_pezeshk <> '0') 
   set @mywhere =@mywhere+' and code_pezeshk='+@code_pezeshk

       if(LEN(@code_darman)>0) 
   set @mywhere =@mywhere+' and code_darman='+@code_darman


       if(LEN(@code_shift)>0) 
   set @mywhere =@mywhere+' and code_shift='+@code_shift


       if(LEN(@code_user_insert)>0) 
   set @mywhere =@mywhere+' and code_user_insert='+@code_user_insert


       if(LEN(@code_pay)>0) 
   set @mywhere =@mywhere+' and code_pay='+@code_pay


       if(LEN(@code_shobeh)>0) 
   set @mywhere =@mywhere+' and code_shobeh='+@code_shobeh



   if(LEN(@from_time)>0) and (LEN(@to_time)>0) 
   set @mywhere =@mywhere+' and insert_time between '''+@from_time+''''+' and '+''''+@to_time+''''


   if(LEN(@sh_kargozini)>0) 
   set @mywhere =@mywhere+' and sh_kargozini='''+@sh_kargozini+''''


    if(LEN(@code_ertebat)>0) 
   set @mywhere =@mywhere+' and code_ertebat='''+@code_ertebat+''''

   if(LEN(@code_shift_str)>0) 
   set @mywhere =@mywhere+@code_shift_str


   if(LEN(@code_bimeh_str)>0) 
   set @mywhere =@mywhere+@code_bimeh_str


   if(LEN(@code_bakhsh_str)>0) 
   set @mywhere =@mywhere+@code_bakhsh_str



   if(LEN(@code_pezeshk_str)>0) 
   set @mywhere =@mywhere+@code_pezeshk_str


   if(LEN(@code_yaraneh)>0) 
   set @mywhere =@mywhere+' and code_yaraneh='+@code_yaraneh



   if(LEN(@code_mokammel)>0) 
   set @mywhere =@mywhere+' and code_mokammel='+@code_mokammel


    if(LEN(@code_dastyar)>0) 
   set @mywhere =@mywhere+' and code_dastyar='+@code_dastyar


   if(LEN(@code_ranandeh)>0) 
   set @mywhere =@mywhere+' and code_ranandeh='+@code_ranandeh

    
 
  -- set @mygroup=' group by code_pezeshk '
  
  -- set @myorder=' order by code_pezeshk '

	  
   set @mystmt= @mystmt+@mywhere+@mygroup+@myorder

  --  select @mystmt

   exec (@mystmt)



END
Go
IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_with_para_4_' AND type = 'P')
   DROP PROCEDURE sp_report_with_para_4_
Go 


alter PROCEDURE [dbo].[sp_report_with_para_4_] (
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10),
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),
@code_ertebat varchar(10),
@code_shift_str varchar(5000),
@code_bimeh_str varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),
@code_mokammel varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10))
AS
  -- از بین بردن فضای خالی
  SET @from_tarikh = LTRIM(RTRIM(@from_tarikh));
  SET @to_tarikh = LTRIM(RTRIM(@to_tarikh));
  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @code_darman = LTRIM(RTRIM(@code_darman));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));
  SET @code_pay = LTRIM(RTRIM(@code_pay));
  SET @code_shobeh = LTRIM(RTRIM(@code_shobeh));
  SET @from_time = LTRIM(RTRIM(@from_time));
  SET @to_time = LTRIM(RTRIM(@to_time));
  SET @sh_kargozini = LTRIM(RTRIM(@sh_kargozini));
  SET @code_ertebat = LTRIM(RTRIM(@code_ertebat));
  SET @code_shift_str = LTRIM(RTRIM(@code_shift_str));
  SET @code_bimeh_str = LTRIM(RTRIM(@code_bimeh_str));
  SET @code_bakhsh_str = LTRIM(RTRIM(@code_bakhsh_str));
  SET @code_pezeshk_str = LTRIM(RTRIM(@code_pezeshk_str));
  SET @code_yaraneh = LTRIM(RTRIM(@code_yaraneh));
  SET @code_mokammel = LTRIM(RTRIM(@code_mokammel));
  SET @code_dastyar = LTRIM(RTRIM(@code_dastyar));
  SET @code_ranandeh = LTRIM(RTRIM(@code_ranandeh));

  --  تعریف متغیر ها
  DECLARE @mywhere nvarchar(3000);
  DECLARE @mystmt nvarchar(3000);
  DECLARE @mygroup nvarchar(500);
  DECLARE @myorder nvarchar(500);


  --  از حالت نال در اوردن 
  SET @mywhere = ''
  SET @mystmt = ''
  SET @mygroup = ''
  SET @myorder = ''


  BEGIN

    SET @mywhere = @mywhere + ' where 1> 0 ';

    IF (LEN(@from_tarikh) > 0)
      AND (LEN(@to_tarikh) > 0)
      SET @mywhere = @mywhere + ' and tarikh between ''' + @from_tarikh + '''' + ' and ' + '''' + @to_tarikh + ''''

    IF (LEN(@code_bimar) > 0)
      SET @mywhere = @mywhere + ' and code_bimar=' + @code_bimar

    IF (LEN(@code_bimeh) > 0)
      SET @mywhere = @mywhere + ' and code_bimeh=' + @code_bimeh


    IF (LEN(@code_bakhsh) > 0)
      SET @mywhere = @mywhere + ' and code_bakhsh=' + @code_bakhsh


    IF (LEN(@code_pezeshk) > 0)
      AND (@code_pezeshk <> '0')
      SET @mywhere = @mywhere + ' and code_pezeshk=' + @code_pezeshk

    IF (LEN(@code_darman) > 0)
      SET @mywhere = @mywhere + ' and code_darman=' + @code_darman


    IF (LEN(@code_shift) > 0)
      SET @mywhere = @mywhere + ' and code_shift=' + @code_shift


    IF (LEN(@code_user_insert) > 0)
      SET @mywhere = @mywhere + ' and code_user_insert=' + @code_user_insert


    IF (LEN(@code_pay) > 0)
      SET @mywhere = @mywhere + ' and code_pay=' + @code_pay


    IF (LEN(@code_shobeh) > 0)
      SET @mywhere = @mywhere + ' and code_shobeh=' + @code_shobeh



    IF (LEN(@from_time) > 0)
      AND (LEN(@to_time) > 0)
      SET @mywhere = @mywhere + ' and insert_time between ''' + @from_time + '''' + ' and ' + '''' + @to_time + ''''


    IF (LEN(@sh_kargozini) > 0)
      SET @mywhere = @mywhere + ' and sh_kargozini=''' + @sh_kargozini + ''''


    IF (LEN(@code_ertebat) > 0)
      SET @mywhere = @mywhere + ' and code_ertebat=''' + @code_ertebat + ''''

    IF (LEN(@code_shift_str) > 0)
      SET @mywhere = @mywhere + @code_shift_str


    IF (LEN(@code_bimeh_str) > 0)
      SET @mywhere = @mywhere + @code_bimeh_str


    IF (LEN(@code_bakhsh_str) > 0)
      SET @mywhere = @mywhere + @code_bakhsh_str



    IF (LEN(@code_pezeshk_str) > 0)
      SET @mywhere = @mywhere + @code_pezeshk_str


    IF (LEN(@code_yaraneh) > 0)
      SET @mywhere = @mywhere + ' and code_yaraneh=' + @code_yaraneh



    IF (LEN(@code_mokammel) > 0)
      SET @mywhere = @mywhere + ' and code_mokammel=' + @code_mokammel


    IF (LEN(@code_dastyar) > 0)
      SET @mywhere = @mywhere + ' and code_dastyar=' + @code_dastyar


    IF (LEN(@code_ranandeh) > 0)
      SET @mywhere = @mywhere + ' and code_ranandeh=' + @code_ranandeh



    SET @mystmt = 'SELECT
  code_pezeshk,
  (SELECT
    name_pezeshk
  FROM pezeshkan
  WHERE code_pezeshk = m.code_pezeshk)
  AS name_pezeshk,
  (SELECT
    darsad
  FROM pezeshkan
  WHERE code_pezeshk = m.code_pezeshk)
  AS darsad_pezeshk,
  SUM(r_bimeh + r_bes) AS jam,
  CASE
    WHEN (SELECT
        darsad
      FROM pezeshkan
      WHERE code_pezeshk = m.code_pezeshk)
      <= 20 OR
      (SELECT
        darsad
      FROM pezeshkan
      WHERE code_pezeshk = m.code_pezeshk)
      IS NULL THEN SUM(r_bimeh + r_bes)
    ELSE SUM(r_bimeh + r_bes) * (SELECT
        darsad
      FROM pezeshkan
      WHERE code_pezeshk = m.code_pezeshk)
      / 100
  END
  AS sahme_pezeshk,
  CASE
    WHEN (SELECT
        darsad
      FROM pezeshkan
      WHERE code_pezeshk = m.code_pezeshk)
      <= 20 OR
      (SELECT
        darsad
      FROM pezeshkan
      WHERE code_pezeshk = m.code_pezeshk)
      IS NULL THEN 0
    ELSE SUM(r_bimeh + r_bes) - (SUM(r_bimeh + r_bes) * (SELECT
        darsad
      FROM pezeshkan
      WHERE code_pezeshk = m.code_pezeshk)
      / 100)
  END
  AS sahme_clinic
FROM morajeat m '


    SET @mygroup = ' group by code_pezeshk '

    SET @myorder = ' order by code_pezeshk '


    SET @mystmt = @mystmt + @mywhere + @mygroup + @myorder

    --  select @mystmt

    EXEC (@mystmt)

  END
  Go
--1398/07/13
CREATE TABLE [dbo].[masraf_daro_itm](
	[id_itm] [int] IDENTITY(1,1) NOT NULL,
	[id_hdr] [int] NOT NULL,
	[code_kala] [int] NOT NULL,
	[doze] [float] NOT NULL,
	[sobeh] [float] NULL,
	[zohre] [float] NULL,
	[asr] [float] NULL,
	[shab] [float] NULL,
	[sharh] nvarchar(500) NULL,
	[code_user_insert] [int] NULL ,
	[insert_time] [datetime] NULL ,
	[code_user_edit] [int] NULL ,
	[edit_time] [datetime] NULL ,
	[code_shift] [int] NULL ,
	[code_shobeh] [int] NULL 

 CONSTRAINT [PK_masraf_daro_itm] PRIMARY KEY CLUSTERED 
(
	[id_itm] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[masraf_daro_hdr](
	[id_hdr] [int] IDENTITY(1,1) NOT NULL,
	[code_bimar] [int] NOT NULL,
	[tarikh] [char](10) NOT NULL,
	[code_user_insert] [int] NULL ,
	[insert_time] [datetime] NULL ,
	[code_user_edit] [int] NULL ,
	[edit_time] [datetime] NULL ,
	[code_shift] [int] NULL ,
	[code_shobeh] [int] NULL 

 CONSTRAINT [PK_masraf_daro_hdr] PRIMARY KEY CLUSTERED 
(
	[id_hdr] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

--1398/07/14

ALTER TABLE [dbo].[kala]
   ADD [masraf_daro] [bit] NULL 
Go
update kala set masraf_daro=0 where masraf_daro is null
Go
update bimaran set code_meli=code_bimar where ((code_meli is Null) or LEN(LTRIM(RTRIM(code_meli)))=0)
Go
Update bimaran set unid=code_meli where ((unid is Null) or LEN(LTRIM(RTRIM(unid)))=0)
Go

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = '_sp_vaght_dehi_befor_Save_' AND type = 'P')
   DROP PROCEDURE _sp_vaght_dehi_befor_Save_
Go 

Go

Create PROCEDURE [dbo].[_sp_vaght_dehi_befor_Save_] (
-- 1398/07/14 by Ali Chamani NeedSoft
@code_bimar varchar(10),
@code_pezeshk varchar(10),
@tarikh_vaght char(10),
@saat_vaght char(5),
@meghdar_vaght varchar(10),
@code_unit varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_darman varchar(10),
@allow_save char(1) OUTPUT,
@s_message varchar(500) OUTPUT)
AS

  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @tarikh_vaght = LTRIM(RTRIM(@tarikh_vaght));
  SET @saat_vaght = LTRIM(RTRIM(@saat_vaght));
  SET @meghdar_vaght = LTRIM(RTRIM(@meghdar_vaght));
  SET @code_unit = LTRIM(RTRIM(@code_unit));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_darman = LTRIM(RTRIM(@code_darman));

  SET @allow_save = '0';
  SET @s_message = '';

  DECLARE @unit_is_full char(1)
  SET @unit_is_full = '0';

  BEGIN
    IF EXISTS (SELECT
        *
      FROM vaght_dehi
      WHERE 1 > 0
     -- AND code_bimar = @code_bimar
     -- AND code_pezeshk = @code_pezeshk
      AND tarikh = @tarikh_vaght
      AND saat = @saat_vaght
      AND code_unit = @code_unit)
    BEGIN
      SET @unit_is_full = '1'
      SET @s_message = @s_message + '  با این مشخصات یونیت  مورد نظر پر میباشد  '
    END
    ELSE
    BEGIN
      SET @unit_is_full = '0'
      SET @s_message = @s_message + '  با این مشخصات یونیت  مورد نظر آزاد میباشد  '
    END

    IF @unit_is_full = 1
      SET @allow_save = 0
    ELSE
      SET @allow_save = 1

  END;
-- 1398/06/24 by Ali Chamani NeedSoft
-- EXEC
/*

DECLARE @allow_save char(1) ;
DECLARE @s_message varchar(500) ;


exec _sp_vaght_dehi_befor_Save_  
 @code_bimar='29128'  ,
 @code_pezeshk='63749'  ,
 @tarikh_vaght='1398/07/15'  ,
 @saat_vaght='10:10' ,
 @meghdar_vaght=''  ,
 @code_unit='1'  ,
 @code_bimeh='2'  ,
 @code_bakhsh=''  ,
 @code_darman='1669',

 @allow_save=@allow_save  OUTPUT,
 @s_message=@s_message  OUTPUT
	

	
	select
	    '  @allow_save='+LTRIM(STR(@allow_save))+CHAR(13)+ 
        '   @s_message='+LTRIM( @s_message) 

*/
Go

--  1398/07/20
--  کنترل ثبت اطلاعات در مراجعات و وقت دهی قبل از ثبت و بعد از ان 

ALTER TABLE [dbo].[settingc]
    add [check_sp_vaght_dehi_befor_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_vaght_dehi_after_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_morajeat_after_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_morajeat_befor_Save_] bit Null
Go

--  update settingc set check_sp_vaght_dehi_befor_Save_=1
Go
--  update settingc set check_sp_vaght_dehi_after_Save_=1
Go
--  update settingc set check_sp_morajeat_befor_Save_=1
Go
--  update settingc set check_sp_morajeat_befor_Save_=1
Go

-- برای تست چک کردن بیمار که در لیست دیگری موجوذ باشد

CREATE TABLE [dbo].[_list_bimar_] (
	[code_meli] [nvarchar] (50)  NOT NULL ,
	[name] [nvarchar] (50)  NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[_list_bimar_] WITH NOCHECK ADD 
	CONSTRAINT [PK__list_bimar_] PRIMARY KEY  CLUSTERED 
	(
		[code_meli]
	)  ON [PRIMARY] 
GO
  -----

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = '_sp_morajeat_befor_Save_' AND type = 'P')
   DROP PROCEDURE _sp_morajeat_befor_Save_
Go   


create PROCEDURE [dbo].[_sp_morajeat_befor_Save_] (
-- 1398/07/20 by Ali Chamani NeedSoft
@code_bimar varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@tarikh_m char(10),
@code_yaraneh varchar(10),
@code_mokammel varchar(10),
@code_dastyar varchar(10),
@code_shift varchar(10),
@code_user_insert varchar(10),

@allow_save char(1) OUTPUT,
@s_message varchar(500) OUTPUT)
AS

  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_darman = LTRIM(RTRIM(@code_darman));
  SET @tarikh_m = LTRIM(RTRIM(@tarikh_m));
  SET @code_yaraneh = LTRIM(RTRIM(@code_yaraneh));
  SET @code_mokammel = LTRIM(RTRIM(@code_mokammel));
  SET @code_dastyar = LTRIM(RTRIM(@code_dastyar));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));

  SET @allow_save = '0';
  SET @s_message = '';

  DECLARE @code_meli char(10)
  SET @code_meli = '';

  BEGIN
    IF (LEN(@code_bimar) > 0)
      AND (LEN(@code_bimeh) > 0)
    BEGIN
      SELECT
        @code_meli = code_meli
      FROM bimaran
      WHERE code_bimar = @code_bimar
      IF LEN(LTRIM(RTRIM(@code_meli))) = 10
      BEGIN
        IF EXISTS (SELECT
            *
          FROM _list_bimar_
          WHERE code_meli = @code_meli)
        BEGIN
          SET @allow_save = '1'
          SET @s_message = @s_message + ' :)  اسم بیمار در لیست دوم وجود دارد    '
        END
        ELSE
        BEGIN
          SET @allow_save = '0'
          SET @s_message = @s_message + ' ):  اسم بیمار در لیست دوم موجود نیست    '
        END;
      END
      ELSE
      BEGIN
        SET @allow_save = '0'
        SET @s_message = @s_message + ' در لیست اصلی کد ملی کمتر از 10 کاراکتر یا نامعتبر است   '
      END;
    END
    ELSE
    BEGIN
      SET @allow_save = '0'
      SET @s_message = @s_message + ' کد بیمار یا کد بیمه ورودی اس پی  معتبر نمی باشد  '
    END;
  END;
-- 1398/07/20 by Ali Chamani NeedSoft
-- EXEC
/*


DECLARE		@allow_save char(1)
DECLARE		@s_message varchar(500)

EXEC	_sp_morajeat_befor_Save_
		@code_bimar = NULL,
		@code_bimeh = NULL,
		@code_bakhsh = NULL,
		@code_pezeshk = NULL,
		@code_darman = NULL,
		@tarikh_m = NULL,
		@code_yaraneh = NULL,
		@code_mokammel = NULL,
		@code_dastyar = NULL,
		@code_shift = NULL,
		@code_user_insert = NULL,
		@allow_save = @allow_save OUTPUT,
		@s_message = @s_message OUTPUT

SELECT	@allow_save as N'@allow_save',
		@s_message as N'@s_message'


GO
*/

-- 1398/08/08

CREATE TABLE [dbo].[settinge](
	[id] [int] NOT NULL,
 CONSTRAINT [PK_settinge] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
insert settinge (id) values (1)
Go
CREATE TABLE [dbo].[settingd](
	[id] [int] NOT NULL,
 CONSTRAINT [PK_settingd] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
insert settingd (id) values (1)

Go


ALTER TABLE [dbo].[settingd]
    add [no_select_shift] bit Null
Go
update settingd set no_select_shift=0 where no_select_shift is  null
-- update settingd set no_select_shift=1
GO
ALTER TABLE [dbo].[settingd]
    add [no_entekhab_sarye_kala_toch] bit Null
Go
update settingd set no_entekhab_sarye_kala_toch=0 where no_entekhab_sarye_kala_toch is  null
-- update settingd set no_entekhab_sarye_kala_toch=1 
Go

ALTER TABLE [dbo].[settingd]
    add [no_checking_on_program_exit] bit Null
Go
update settingd set no_checking_on_program_exit=0 where no_checking_on_program_exit is  null
-- update settingd set no_checking_on_program_exit=1 
Go

INSERT INTO Noa_Anbar (Code_Noa_Anbar
, Name_Noa_Anbar
, Code_In_Out
, Onvan_Anbar
, Taraf_Moghabel
, Kardex
, Sabt_Sanad)
  VALUES (4, 'حواله ورود ', 1, 'انبار تحویل گیرنده', 'طرف حساب', 0, 0)
GO
INSERT INTO Noa_Anbar (Code_Noa_Anbar
, Name_Noa_Anbar
, Code_In_Out
, Onvan_Anbar
, Taraf_Moghabel
, Kardex
, Sabt_Sanad)
  VALUES (5, 'حواله خروج ', 2, 'انبار تحویل دهنده', 'طرف حساب', 0, 0)
GO
INSERT INTO Noa_Anbar (Code_Noa_Anbar
, Name_Noa_Anbar
, Code_In_Out
, Onvan_Anbar
, Taraf_Moghabel
, Kardex
, Sabt_Sanad)
  VALUES (6, 'رسید امانی ', 1, 'انبار تحویل گیرنده', 'طرف حساب', 0, 0)
GO
INSERT INTO Noa_Anbar (Code_Noa_Anbar
, Name_Noa_Anbar
, Code_In_Out
, Onvan_Anbar
, Taraf_Moghabel
, Kardex
, Sabt_Sanad)
  VALUES (7, 'خروج امانی ', 2, 'انبار تحویل دهنده', 'طرف حساب', 0, 0)
GO
INSERT INTO Noa_Anbar (Code_Noa_Anbar
, Name_Noa_Anbar
, Code_In_Out
, Onvan_Anbar
, Taraf_Moghabel
, Kardex
, Sabt_Sanad)
  VALUES (8, 'پیش فاکتور فروش ', 0, 'انبار تحویل دهنده', 'طرف حساب', 0, 0)
GO

IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_report_Anbar_1')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N' گزارش نمونه انبار 1  ', 'sp_report_Anbar_1', 'sp_report_Anbar_1.fr3', 1, 'sp_parameters', 1,2)
END
Go

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_report_anbar_1' AND type = 'P')
   DROP PROCEDURE sp_report_anbar_1
Go  

CREATE PROCEDURE [dbo].[sp_report_anbar_1] (
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_kala varchar(10),
@code_anbar varchar(10),
@code_noa_anbar varchar(10),
@Code_In_Out varchar(10),
@code_tafzil varchar(10),
@code_goroh_kala varchar(10),
@code_tabagheh_kala varchar(10),
@code_noa_kala varchar(10),
@code_pa varchar(10),
@code_pb varchar(10),
@code_shift varchar(10),
@code_user_insert varchar(10),
@code_shobeh varchar(10),
@from_exp_tarikh char(10),
@to_exp_tarikh char(10),
@from_time varchar(20),
@to_time varchar(20))
AS
  -- از بین بردن فضای خالی
  SET @from_tarikh = LTRIM(RTRIM(@from_tarikh));
  SET @to_tarikh = LTRIM(RTRIM(@to_tarikh));
  SET @code_kala = LTRIM(RTRIM(@code_kala));
  SET @code_anbar = LTRIM(RTRIM(@code_anbar));
  SET @code_noa_anbar = LTRIM(RTRIM(@code_noa_anbar));
  SET @Code_In_Out = LTRIM(RTRIM(@Code_In_Out));
  SET @code_tafzil = LTRIM(RTRIM(@code_tafzil));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));
  SET @code_goroh_kala = LTRIM(RTRIM(@code_goroh_kala));
  SET @code_shobeh = LTRIM(RTRIM(@code_shobeh));
  SET @from_time = LTRIM(RTRIM(@from_time));
  SET @to_time = LTRIM(RTRIM(@to_time));
  SET @code_tabagheh_kala = LTRIM(RTRIM(@code_tabagheh_kala));
  SET @code_noa_kala = LTRIM(RTRIM(@code_noa_kala));
  SET @code_pa = LTRIM(RTRIM(@code_pa));
  SET @code_pb = LTRIM(RTRIM(@code_pb));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));
  SET @code_shobeh = LTRIM(RTRIM(@code_shobeh));
  SET @from_exp_tarikh = LTRIM(RTRIM(@from_exp_tarikh));
  SET @to_exp_tarikh = LTRIM(RTRIM(@to_exp_tarikh));
  SET @from_time = LTRIM(RTRIM(@from_time));
  SET @to_time = LTRIM(RTRIM(@to_time));
  --  تعریف متغیر ها   --  از حالت نال در اوردن 
  DECLARE @mywhere nvarchar(3000) = '';
  DECLARE @mystmt nvarchar(3000) = '';
  DECLARE @mygroup nvarchar(500) = '';
  DECLARE @myorder nvarchar(500) = '';

  BEGIN

    SET @mystmt = 'select * from anbar_itm '

    SET @mywhere = @mywhere + ' where 1> 0 ';


    IF (LEN(@from_tarikh) > 0)
      AND (LEN(@to_tarikh) > 0)
      SET @mywhere = @mywhere + ' and tarikh between ''' + @from_tarikh + '''' + ' and ' + '''' + @to_tarikh + ''''

    IF (LEN(@code_kala) > 0)
      SET @mywhere = @mywhere + ' and code_kala=' + @code_kala


    IF (LEN(@code_shift) > 0)
      SET @mywhere = @mywhere + ' and code_shift=' + @code_shift


    IF (LEN(@code_user_insert) > 0)
      SET @mywhere = @mywhere + ' and code_user_insert=' + @code_user_insert


    IF (LEN(@code_shobeh) > 0)
      SET @mywhere = @mywhere + ' and code_shobeh=' + @code_shobeh


    IF (LEN(@from_time) > 0)
      AND (LEN(@to_time) > 0)
      SET @mywhere = @mywhere + ' and insert_time between ''' + @from_time + '''' + ' and ' + '''' + @to_time + ''''


    -- set @mygroup=' group by code_pezeshk '

    -- set @myorder=' order by code_pezeshk '


    SET @mystmt = @mystmt + @mywhere + @mygroup + @myorder

    --  select @mystmt

    EXEC (@mystmt)

  END

  Go



--  for Onley  Anbar  فقط انبار 
-- update settingd set no_select_shift=1
-- update setting  set Sabte_Daem_Morajat_Gozashte=0
-- update setting  set alarm_hade_taghaza_anbar=1
-- update setting  set show_menu_parvandeh=0   
-- update setting  set show_menu_Sayer_Amaliat=0  
-- update setting  set show_gozareshat_bimeh=0  
-- update setting  set  show_bimarestan=0
-- update setting  set  show_tanzimat=0
-- update setting  set  show_Panel_LEFT_MainForm=0
-- update settingd set  no_entekhab_sarye_kala_toch=1 
-- update settingd set  no_checking_on_program_exit=1 
-- update setting  set  show_Foto_Terapi=0 
-- update setting  set  show_daro_paziresh=0
-- update setting  set  onvan='  برنامه انبار داری '
-- update setting  set  address='     برنامه نمونه انبارداری  نمونه  '
-- update setting  set  onvan_latin=' Anbar Nemoneh 1398  '

Go

ALTER TABLE [dbo].[settingd]
    add [select_noa_pay_bimar_sarpaei] bit Null
Go
update settingd set select_noa_pay_bimar_sarpaei=0 where select_noa_pay_bimar_sarpaei is  null
-- update settingd set select_noa_pay_bimar_sarpaei=1 
Go

IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_havale_khoroj_kala_pakage_koli_alich13980826')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N' حواله خروج  اتوماتیک درمانهای دارای تعریف پکیج از پذیرش  ', 'sp_havale_khoroj_kala_pakage_koli_alich13980826', 'sp_havale_khoroj_kala_pakage_koli_alich13980826.fr3', 1, 'sp_parameters', 1,1)
END
Go


declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_havale_khoroj_kala_pakage_koli_alich13980826' AND type = 'P')
	 begin
	 set @old_name='sp_havale_khoroj_kala_pakage_koli_alich13980826'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_havale_khoroj_kala_pakage_koli_alich13980826',@old_name;
   end
Go
create PROCEDURE [dbo].[sp_havale_khoroj_kala_pakage_koli_alich13980826] (
-- sp_havale_khoroj_kala_pakage_koli by alich 1398/08/26
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10),
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),
@code_ertebat varchar(10),
@code_shift_str varchar(5000),
@code_bimeh_str varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),
@code_mokammel varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10))
AS
  -- از بین بردن فضای خالی
  SET @from_tarikh = LTRIM(RTRIM(@from_tarikh));
  SET @to_tarikh = LTRIM(RTRIM(@to_tarikh));
  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @code_darman = LTRIM(RTRIM(@code_darman));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));
  SET @code_pay = LTRIM(RTRIM(@code_pay));
  SET @code_shobeh = LTRIM(RTRIM(@code_shobeh));
  SET @from_time = LTRIM(RTRIM(@from_time));
  SET @to_time = LTRIM(RTRIM(@to_time));
  SET @sh_kargozini = LTRIM(RTRIM(@sh_kargozini));
  SET @code_ertebat = LTRIM(RTRIM(@code_ertebat));
  SET @code_shift_str = LTRIM(RTRIM(@code_shift_str));
  SET @code_bimeh_str = LTRIM(RTRIM(@code_bimeh_str));
  SET @code_bakhsh_str = LTRIM(RTRIM(@code_bakhsh_str));
  SET @code_pezeshk_str = LTRIM(RTRIM(@code_pezeshk_str));
  SET @code_yaraneh = LTRIM(RTRIM(@code_yaraneh));
  SET @code_mokammel = LTRIM(RTRIM(@code_mokammel));
  SET @code_dastyar = LTRIM(RTRIM(@code_dastyar));
  SET @code_ranandeh = LTRIM(RTRIM(@code_ranandeh));

  DECLARE @s_mess nvarchar(4000)='';

  BEGIN
 
    set @s_mess=@s_mess+' @from_tarikh='+@from_tarikh
	set @s_mess=@s_mess+' @to_tarikh='+@to_tarikh
	set @s_mess=@s_mess+' @code_user_insert='+@code_user_insert
	set @s_mess=@s_mess+' @code_shift='+@code_shift

    IF ((LEN(@from_tarikh) = 10)
      AND (LEN(@to_tarikh) = 10)
      AND (@code_user_insert > 0)
      AND (@code_shift > 0))
	  BEGIN
      IF EXISTS (SELECT
          code_morajeh
        FROM morajeat
        WHERE tarikh BETWEEN @from_tarikh AND @to_tarikh
        AND code_user_insert = @code_user_insert
        AND code_shift = code_shift
        AND ID_Anbar_Hdr < 1
        AND code_darman IN (SELECT
          code_darman
        FROM Anbar_Itm_Set_Masraf_Darman
        GROUP BY code_darman))
      BEGIN

	    DECLARE @Code_Tafzil char(10)
		select @Code_Tafzil=Code_Tafzil_Masraf_Daro from setting

        DECLARE @Code_Anbar int
		select @Code_Anbar=Code_Anbar_Masraf_Daro from setting
	

		DECLARE @Code_Noa_Anbar int=2
        DECLARE @code_morajeh int
        DECLARE @tarikh_morajeh char(10)
		DECLARE @code_darman_morajeh int
		DECLARE @code_bimar_morajeh int
        DECLARE @code_pezeshk_morajeh int
        DECLARE @tedad_darman_morajeh int

        DECLARE @radif_masraf int
        DECLARE @Code_Kala_masraf int
        DECLARE @Code_Uni_masraft int
        DECLARE @qout_masraf int
        DECLARE @fi_masraf int
        DECLARE @Jam_masraf int
        DECLARE @max_ID_Anbar_Hdr int
		DECLARE @Anbar_Hdr_inserted int=0
		DECLARE @Anbar_itm_inserted int=0

        DECLARE cursor_morajeat CURSOR FAST_FORWARD FOR
        SELECT
          code_morajeh,
          tarikh,
		  code_bimar,
		  code_pezeshk,
          code_darman,
          tedad_darman
        FROM morajeat
        WHERE tarikh BETWEEN @from_tarikh AND @to_tarikh
        AND code_user_insert = @code_user_insert
        AND code_shift = code_shift
        AND ID_Anbar_Hdr < 1
        ORDER BY code_morajeh DESC

        OPEN cursor_morajeat
        FETCH NEXT FROM cursor_morajeat INTO @code_morajeh, @tarikh_morajeh,@code_bimar_morajeh,@code_pezeshk_morajeh,@code_darman_morajeh, @tedad_darman_morajeh
        -- loop 
        WHILE @@FETCH_STATUS = 0
        BEGIN
          IF EXISTS (SELECT
              Code_Kala
            FROM Anbar_Itm_Set_Masraf_Darman
            WHERE code_darman = @code_darman_morajeh)
          BEGIN

                    if exists(select top 1 ID_Anbar_Hdr from Anbar_Hdr  )
		           SELECT
                   @max_ID_Anbar_Hdr = MAX(ID_Anbar_Hdr)+1
                   FROM Anbar_Hdr
			       else set @max_ID_Anbar_Hdr=1


            INSERT Anbar_Hdr (ID_Anbar_Hdr, Num_Anbar_Hdr,tarikh,Code_Anbar, Code_Tafzil, Code_Noa_Anbar, Code_User_Insert,Insert_Time, Jam, Ezaf, Kasr, Kol, Sharh)
              VALUES (@max_ID_Anbar_Hdr, 0,@tarikh_morajeh,@Code_Anbar,@Code_Tafzil,@Code_Noa_Anbar, @code_user_insert, GETDATE(),0, 0, 0, 0, @tarikh_morajeh+'  code_bimar='+STR(@code_bimar_morajeh)+'  code_pezeshk='+STR(@code_pezeshk_morajeh)+'  code_morajeh'+STR(@code_morajeh))
           
            if @@ROWCOUNT=1
		    update morajeat set ID_Anbar_Hdr=@max_ID_Anbar_Hdr where code_morajeh=@code_morajeh

			set @Anbar_Hdr_inserted=@Anbar_Hdr_inserted+1

            DECLARE cursor_masraf CURSOR FAST_FORWARD FOR
            SELECT
              radif,
              Code_Kala,
              Code_Unit,
              qout,
              fi,
              Jam
            FROM Anbar_Itm_Set_Masraf_Darman
            WHERE code_darman = @code_darman_morajeh

            OPEN cursor_masraf
            FETCH NEXT FROM cursor_masraf INTO @radif_masraf, @Code_Kala_masraf, @Code_Uni_masraft, @qout_masraf, @fi_masraf, @Jam_masraf
            WHILE @@FETCH_STATUS = 0
            BEGIN

              INSERT Anbar_Itm (ID_Anbar_Hdr,Num_Anbar_Hdr, Code_Tafzil, Code_Noa_Anbar, Code_Anbar, Tarikh, Radif, Code_Kala, code_unit, kardex, qin, qout, Fi, Jam, sharh, Code_User_Insert, Insert_Time)
               VALUES (@max_ID_Anbar_Hdr,0,@Code_Tafzil,@Code_Noa_Anbar,@Code_Anbar, @tarikh_morajeh, @radif_masraf, @Code_Kala_masraf, @Code_Uni_masraft, 1, 0, @qout_masraf, @fi_masraf, @Jam_masraf,@tarikh_morajeh+'  code_bimar='+STR(@code_bimar_morajeh)+'  code_pezeshk='+STR(@code_pezeshk_morajeh)+'  code_morajeh'+STR(@code_morajeh), @code_user_insert, GETDATE())

                set @Anbar_itm_inserted=@Anbar_itm_inserted+1 

              FETCH NEXT FROM cursor_masraf INTO @radif_masraf, @Code_Kala_masraf, @Code_Uni_masraft, @qout_masraf, @fi_masraf, @Jam_masraf
            END

            CLOSE cursor_masraf
            DEALLOCATE cursor_masraf
          END
          -- end inner loop

          FETCH NEXT FROM cursor_morajeat INTO @code_morajeh, @tarikh_morajeh,@code_bimar_morajeh,@code_pezeshk_morajeh,@code_darman_morajeh, @tedad_darman_morajeh
        END
        CLOSE cursor_morajeat
        DEALLOCATE cursor_morajeat
      -- end outter loop
	            SELECT
          @Anbar_Hdr_inserted+@Anbar_itm_inserted AS s_result,
          'Number of Inserted to Anbar_Hdr,Anbar_itm  with :   ' + OBJECT_NAME(@@PROCID)+' '+str(@Anbar_Hdr_inserted)+' '+str(@Anbar_itm_inserted) AS s_message,
		   @s_mess as s_param 
         END
		 ELSE
		 SELECT
          '0' AS s_result,
          'no record in table morajeat  stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 

      END
      ELSE
        SELECT
          '0' AS s_result,
          'no coddition to run stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 
  END

  -- exec sp_havale_khoroj_kala_pakage_koli '1398/08/26','1398/08/27','','','','','',1,1,'','','','','','','','','','','','','',''
  -- delete Anbar_Hdr
  -- delete anbar_itm
  -- update morajeat set ID_Anbar_Hdr=0 ,code_user_insert=14, code_shift=1
  -- update morajeat set tarikh='1398/01/01' where tarikh > '1398/08/26'
  -- update moshtari set tahvil_girandeh_kala=1 , foroshande_kala=1
  /*
  SELECT  tarikh,code_morajeh,code_darman,
    	  code_user_insert,code_shift
        FROM morajeat  where
		 code_darman in (select code_darman from Anbar_Itm_Set_Masraf_Darman group by code_darman )
		 order by tarikh
  */

-- select * from anbar_hdr
-- select * from anbar_itm
-- SELECT * from Noa_Anbar
-- SELECT * from Anbar_Itm_Set_Masraf_Darman
-- select code_morajeh,tarikh,ID_Anbar_Hdr from morajeat order by  ID_Anbar_Hdr DESC


Go




IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_tarif_pakage_for_all_bimeh_alich13980826')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N'  تعریف پکیج مصرف از روی بیمه اصلی برای همه بیمه ها با توجه به کد ارتباط ', 'sp_tarif_pakage_for_all_bimeh_alich13980826', 'sp_tarif_pakage_for_all_bimeh_alich13980826.fr3', 1, 'sp_parameters', 1,1)
END
Go


declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_tarif_pakage_for_all_bimeh_alich13980826' AND type = 'P')
	 begin
	 set @old_name='sp_tarif_pakage_for_all_bimeh_alich13980826'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_tarif_pakage_for_all_bimeh_alich13980826',@old_name;
   end
GO
create PROCEDURE [dbo].[sp_tarif_pakage_for_all_bimeh_alich13980826] (
-- sp_havale_khoroj_kala_pakage_koli by alich 1398/08/26
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10),
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),
@code_ertebat varchar(10),
@code_shift_str varchar(5000),
@code_bimeh_str varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),
@code_mokammel varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10))
AS
  -- از بین بردن فضای خالی
  SET @from_tarikh = LTRIM(RTRIM(@from_tarikh));
  SET @to_tarikh = LTRIM(RTRIM(@to_tarikh));
  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @code_darman = LTRIM(RTRIM(@code_darman));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));
  SET @code_pay = LTRIM(RTRIM(@code_pay));
  SET @code_shobeh = LTRIM(RTRIM(@code_shobeh));
  SET @from_time = LTRIM(RTRIM(@from_time));
  SET @to_time = LTRIM(RTRIM(@to_time));
  SET @sh_kargozini = LTRIM(RTRIM(@sh_kargozini));
  SET @code_ertebat = LTRIM(RTRIM(@code_ertebat));
  SET @code_shift_str = LTRIM(RTRIM(@code_shift_str));
  SET @code_bimeh_str = LTRIM(RTRIM(@code_bimeh_str));
  SET @code_bakhsh_str = LTRIM(RTRIM(@code_bakhsh_str));
  SET @code_pezeshk_str = LTRIM(RTRIM(@code_pezeshk_str));
  SET @code_yaraneh = LTRIM(RTRIM(@code_yaraneh));
  SET @code_mokammel = LTRIM(RTRIM(@code_mokammel));
  SET @code_dastyar = LTRIM(RTRIM(@code_dastyar));
  SET @code_ranandeh = LTRIM(RTRIM(@code_ranandeh));

  DECLARE @s_mess nvarchar(4000)='';
  DECLARE @number_inserted int=0;

  BEGIN
 
    set @s_mess=@s_mess+' @code_bimeh='+@code_bimeh


	if len(@code_bimeh)<>0 
	BEGIN
     IF EXISTS (SELECT top 1 code_darman from Anbar_Itm_Set_Masraf_Darman group by code_darman )
  
	  BEGIN
      IF EXISTS (SELECT
          code_darman,code_ertebat
        FROM darmanha
        WHERE code_bimeh=@code_bimeh
		 and len(Ltrim(Rtrim(code_ertebat)))>0
         and code_darman IN (SELECT
          code_darman
        FROM Anbar_Itm_Set_Masraf_Darman
        GROUP BY code_darman))
      BEGIN

        DECLARE @code_darman_darmanha int
        DECLARE @code_ertebat_darmanha nvarchar(15)
		DECLARE @code_darman_past int

        DECLARE @radif_masraf int
        DECLARE @Code_Kala_masraf int
        DECLARE @Code_Unit_masraf int
        DECLARE @qout_masraf int
        DECLARE @fi_masraf int
        DECLARE @Jam_masraf int

        DECLARE cursor_darmanha CURSOR FAST_FORWARD FOR
        SELECT
          code_darman,code_ertebat
        FROM darmanha
        WHERE  code_bimeh=@code_bimeh
		 and len(Ltrim(Rtrim(code_ertebat)))>0
         and code_darman IN (SELECT
          code_darman
        FROM Anbar_Itm_Set_Masraf_Darman
        GROUP BY code_darman)
		ORDER by code_darman
        OPEN cursor_darmanha
        FETCH NEXT FROM cursor_darmanha INTO @code_darman_darmanha,@code_ertebat_darmanha
        -- loop 
        WHILE @@FETCH_STATUS = 0
        BEGIN

          SELECT
              @code_darman_past=code_darman
            FROM darmanha
            WHERE code_ertebat = @code_ertebat_darmanha
     		if not exists (select top 1 id from Anbar_Itm_Set_Masraf_Darman where code_darman= @code_darman_past)        
          BEGIN
            -- begin inner loop 
            DECLARE cursor_masraf CURSOR FAST_FORWARD FOR
            SELECT
              radif,
              Code_Kala,
              Code_Unit,
              qout,
              fi,
              Jam
            FROM Anbar_Itm_Set_Masraf_Darman
            WHERE code_darman = @code_darman_darmanha

            OPEN cursor_masraf
            FETCH NEXT FROM cursor_masraf INTO @radif_masraf, @Code_Kala_masraf, @Code_Unit_masraf, @qout_masraf, @fi_masraf, @Jam_masraf
            WHILE @@FETCH_STATUS = 0
            BEGIN

			INSERT INTO Anbar_Itm_Set_Masraf_Darman
           (code_darman
           ,radif
           ,Code_Kala
           ,Code_Unit
           ,kardex
		   ,qin
           ,qout
           ,Fi
           ,Jam
           ,code_pezeshk
		   ,Insert_Time)
            VALUES
           (@code_darman_past,@radif_masraf,@Code_Kala_masraf,@Code_Unit_masraf,1,0,@qout_masraf, @fi_masraf, @Jam_masraf,0,GETDATE())

		   if @@ROWCOUNT=1 set @number_inserted=@number_inserted+1
 
            FETCH NEXT FROM cursor_masraf INTO @radif_masraf, @Code_Kala_masraf, @Code_Unit_masraf, @qout_masraf, @fi_masraf, @Jam_masraf
            END

            CLOSE cursor_masraf
            DEALLOCATE cursor_masraf
          END
          -- end inner loop

           FETCH NEXT FROM cursor_darmanha INTO @code_darman_darmanha,@code_ertebat_darmanha
        END
        CLOSE cursor_darmanha
        DEALLOCATE cursor_darmanha
      -- end outter loop
	            SELECT
          str(@number_inserted) AS s_result,
          '(: Number of Inserted to Anbar_Itm_Set_Masraf_Darman  with :   ' + OBJECT_NAME(@@PROCID)+'  '+str(@number_inserted) AS s_message,
		   @s_mess as s_param 
         END
		 ELSE
		 SELECT
          '0' AS s_result,
          '): no record in table darmanha  stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 

      END
      ELSE
        SELECT
          '0' AS s_result,
          '): no record in table Anbar_Itm_Set_Masraf_Darman stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 
    end
	else
	    SELECT
          '0' AS s_result,
          '): no base code_bimeh for copy stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 

  END

  -- exec sp_tarif_pakage_for_all_bimeh_alich13980826  '','','',1,'','','','','','','','','','','','','','','','','','',''
  -- exec sp_tarif_pakage_for_all_bimeh_alich13980826  '','','','','','','','','','','','','','','','','','','','','','',''
 -- select code_darman,code_kala,Insert_Time from Anbar_Itm_Set_Masraf_Darman order by id DESC 
  -- delete Anbar_Itm_Set_Masraf_Darman where code_bimeh <> 1
  -- delete Anbar_Hdr
  -- delete anbar_itm
  -- update morajeat set ID_Anbar_Hdr=0 ,code_user_insert=1, code_shift=1
  -- update morajeat set tarikh='1398/01/01' where tarikh > '1398/08/26'
  -- update moshtari set tahvil_girandeh_kala=1 , foroshande_kala=1
  /*
  SELECT  tarikh,code_morajeh,code_darman,
    	  code_user_insert,code_shift
        FROM morajeat  where
		 code_darman in (select code_darman from Anbar_Itm_Set_Masraf_Darman group by code_darman )
		 order by tarikh
  */

-- select * from anbar_hdr
-- select * from anbar_itm
-- SELECT * from Noa_Anbar
-- SELECT * from Anbar_Itm_Set_Masraf_Darman
-- select code_morajeh,tarikh,ID_Anbar_Hdr from morajeat order by  ID_Anbar_Hdr DESC
Go


declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_all_bimaran_to_Ezdenti' AND type = 'P')
	 begin
	 set @old_name='transfer_all_bimaran_to_Ezdenti'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_all_bimaran_to_Ezdenti',@old_name;
   end
GO
create procedure [dbo].[transfer_all_bimaran_to_Ezdenti]
as
begin

DECLARE @code_bimar int
DECLARE @name nvarchar(50)
DECLARE @famil nvarchar(50)
DECLARE @tavalod char(10)
DECLARE @patint_number_transferred int=0

if exists (SELECT
          code_bimar,
          name,
		  famil,
	      tavalod
        FROM bimaran
        WHERE transferred=0 or transferred is null)
begin
        DECLARE cursor_bimaran CURSOR FAST_FORWARD FOR
        SELECT
          code_bimar,
          name,
		  famil,
	      tavalod
        FROM bimaran
        WHERE transferred=0 or transferred is null
		order by code_bimar
    
        OPEN cursor_bimaran
        FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil,@tavalod

        WHILE @@FETCH_STATUS = 0
        BEGIN


		if not exists (select pat_id from [sqlauth_pg].[E2].[public].[e2_pat]  where  pat_id=@code_bimar )
begin
  insert [sqlauth_pg].[E2].[public].[e2_pat] 
  (pat_id,
  pat_chartno,
  pat_lastname,
  pat_firstname,
  pat_middlename,
  pat_gender,
  pat_birthdate,
  pat_email,
  pat_socialid,
  pat_registered_datetime,
  pat_photo_filename,
  pat_chosung,
  pat_note,
  pat_phone,
  pat_zipcode,
  pat_address)
 values (@code_bimar,@code_bimar,@famil,@name,@name+' '+@famil,0,'1300/01/01',0,0,getdate(),0,0,0,0,0,0)
 end	

     if @@ROWCOUNT=1 
	 begin
	  update bimaran set transferred=1 where code_bimar=@code_bimar
	  set @patint_number_transferred=@patint_number_transferred+1
	 end


  
         FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil,@tavalod
        END
        CLOSE cursor_bimaran
        DEALLOCATE cursor_bimaran

       

end
select @patint_number_transferred as s_result , 'Number Of Inserted='+STR(@patint_number_transferred) +' with sp  ' as s_message ,' param ' as s_param
end

-- exec transfer_all_bimaran_to_Ezdenti
-- select * from [sqlauth_pg].[E2].[public].[e2_pat] order by  pat_id DESC
-- select * from [sqlauth_pg].[E2].[public].[e2_pat]  where pat_id=29134
-- select count(*) from [sqlauth_pg].[E2].[public].[e2_pat]
-- delete [sqlauth_pg].[E2].[public].[e2_pat]
-- update bimaran set transferred=1  
-- update bimaran set transferred=0 where code_bimar < 20
-- select * from bimaran  where code_bimar < 100
-- select COUNT(*) from bimaran where transferred=1
-- select * from test_table order by id DESC

/*
  insert into [sqlauth_pg].[E2].[public].[e2_pat] 
  (pat_id,
  pat_chartno,
  pat_lastname,
  pat_firstname
  )
 (select code_bimar as pat_id ,code_bimar as pat_chartno,famil as pat_lastname,name as pat_firstname from bimaran)

 بیشتر از 100 تا ثبت نمیشه توی  پست گرس 

*/






Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Ezdenti_e2_pat_insert' AND type = 'P')
	 begin
	 set @old_name='sp_Ezdenti_e2_pat_insert'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Ezdenti_e2_pat_insert',@old_name;
   end
GO
create PROCEDURE sp_Ezdenti_e2_pat_insert
(
   @code_bimar varchar(10)
  ,@name nvarchar(50)
  ,@famil nvarchar(50)
  ,@tavalod char(10)

)
as 
begin
if not exists (select pat_id from [sqlauth_pg].[E2].[public].[e2_pat]  where  pat_id=@code_bimar )
begin
  insert [sqlauth_pg].[E2].[public].[e2_pat] 
  (pat_id,
  pat_chartno,
  pat_lastname,
  pat_firstname,
  pat_middlename,
  pat_gender,
  pat_birthdate,
  pat_email,
  pat_socialid,
  pat_registered_datetime,
  pat_photo_filename,
  pat_chosung,
  pat_note,
  pat_phone,
  pat_zipcode,
  pat_address)
 values (@code_bimar,@code_bimar,@name,@famil,@name+' '+@famil,0,'1300/01/01',0,0,getdate(),0,0,0,0,0,0)
 --values (@code_bimar,@code_bimar,@name,@famil,@name+' '+@famil,0,@tavalod,0,0,getdate(),0,0,0,0,0,0)
end	
else
select '0' as s_resault,'Duplicate @code_bimar or  pat_id  in Table [sqlauth_pg].[E2].[public].[e2_pat]  pstgres database '
end

-- exec sp_Ezdenti_e2_pat_insert '1','Ali','Chamani','1355/06/30'
-- select * from [sqlauth_pg].[E2].[public].[e2_pat]
-- delete [sqlauth_pg].[E2].[public].[e2_pat]
--select * from bimaran where code_bimar=28056
/*
  insert into [sqlauth_pg].[E2].[public].[e2_pat] 
  (pat_id,
  pat_chartno,
  pat_lastname,
  pat_firstname
  )
 (select code_bimar as pat_id ,code_bimar as pat_chartno,famil as pat_lastname,name as pat_firstname from bimaran)

 بیشتر از 100 تا ثبت نمیشه توی  پست گرس 

*/
Go


declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_all_bimaran_to_Ezdenti_with_CURSOR_loop' AND type = 'P')
	 begin
	 set @old_name='transfer_all_bimaran_to_Ezdenti_with_CURSOR_loop'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_all_bimaran_to_Ezdenti_with_CURSOR_loop',@old_name;
   end
GO
create procedure transfer_all_bimaran_to_Ezdenti_with_CURSOR_loop
as
begin

DECLARE @code_bimar int
DECLARE @name nvarchar(50)
DECLARE @famil nvarchar(50)
DECLARE @tavalod char(10)
DECLARE @patint_number_transferred int=0

if exists (SELECT
          code_bimar,
          name,
		  famil,
	      tavalod
        FROM bimaran
        WHERE transferred=0 or transferred is null)
begin
        DECLARE cursor_bimaran CURSOR FAST_FORWARD FOR
        SELECT
          code_bimar,
          name,
		  famil,
	      tavalod
        FROM bimaran
        WHERE transferred=0 or transferred is null
		order by code_bimar
    
        OPEN cursor_bimaran
        FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil,@tavalod
        -- first loop 
        WHILE @@FETCH_STATUS = 0
        BEGIN


	     --	if not exists (select pat_id from [sqlauth_pg].[E2].[public].[e2_pat]  where  pat_id=@code_bimar )
	      --	begin
		 exec sp_Ezdenti_e2_pat_insert @code_bimar, @name,@famil,@tavalod
		 set @patint_number_transferred=@patint_number_transferred+1
		 update bimaran set transferred=1 where code_bimar=@code_bimar

     	--	 end
  
           FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil,@tavalod
        END
        CLOSE cursor_bimaran
        DEALLOCATE cursor_bimaran

       

end
select @patint_number_transferred as s_result , 'Number Of Inserted='+STR(@patint_number_transferred) +' with sp  '
end
-- exec transfer_all_bimaran_to_Ezdenti_with_CURSOR_loop
-- select * from [sqlauth_pg].[E2].[public].[e2_pat] 
-- select * from [sqlauth_pg].[E2].[public].[e2_pat]  where pat_id=29134
-- select count(*) from [sqlauth_pg].[E2].[public].[e2_pat]
-- delete [sqlauth_pg].[E2].[public].[e2_pat]
-- update bimaran set transferred=0
-- select COUNT(*) from bimaran where transferred=1

/*
  insert into [sqlauth_pg].[E2].[public].[e2_pat] 
  (pat_id,
  pat_chartno,
  pat_lastname,
  pat_firstname
  )
 (select code_bimar as pat_id ,code_bimar as pat_chartno,famil as pat_lastname,name as pat_firstname from bimaran)

 بیشتر از 100 تا ثبت نمیشه توی  پست گرس 

*/
Go



CREATE TABLE [dbo].[test_table](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[in_date] [datetime] NOT NULL,
	[tcounter] [int] NOT NULL,
 CONSTRAINT [PK_test_table] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'sp_test_job_insert_test_table' AND type = 'P')
   DROP PROCEDURE sp_test_job_insert_test_table
Go  

GO
create procedure sp_test_job_insert_test_table
as
begin
declare @i int=0
  while @i < 5 
  begin
   insert test_table (in_date,tcounter) values (GETDATE(), @i)
    set @i=@i+1
   end
end;
-- exec sp_test_job_insert_test_table
-- select * from test_table order by id DESC
Go



declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Easydent4_injek_insert' AND type = 'P')
	 begin
	 set @old_name='sp_Easydent4_injek_insert'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Easydent4_injek_insert',@old_name;
   end
Go

create procedure sp_Easydent4_injek_insert
(
   @code_bimar varchar(10)
  ,@name nvarchar(50)
  ,@famil nvarchar(50)
)
as
begin

  set @code_bimar=ltrim(rtrim(@code_bimar))
  set @name=ltrim(rtrim(@name))
  set @famil=ltrim(rtrim(@famil))
 
  if (LEN(@code_bimar)>0 ) and (LEN(@name)+LEN(@famil)> 2) 
  begin
  
 if not exists (select chart from [TSFD].[dbo].[injek]  where chart=@code_bimar )
begin 

  insert [TSFD].[dbo].[injek] 
  (
   chart
   ,oldchart
   ,name
  )
 values (@code_bimar,@code_bimar,@name+' '+@famil)

end	
else
select '0' as s_resault,'Duplicate @code_bimar or  chart  in Table [TSFD].[dbo].[injek]  '
end
end
-- exec sp_Easydent4_injek_insert 2,'Ali','Chamani'
-- select * from [TSFD].[dbo].[injek] order by chart DESC

Go



declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_all_bimaran_to_Easydent4_injek' AND type = 'P')
	 begin
	 set @old_name='transfer_all_bimaran_to_Easydent4_injek'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_all_bimaran_to_Easydent4_injek',@old_name;
   end
Go
create procedure [dbo].[transfer_all_bimaran_to_Easydent4_injek]
as
begin

DECLARE @code_bimar int
DECLARE @name nvarchar(50)
DECLARE @famil nvarchar(50)
DECLARE @patint_number_transferred int=0

if exists (SELECT top 1
          code_bimar
        FROM bimaran
        WHERE transferred=0 or transferred is null)
begin
        DECLARE cursor_bimaran CURSOR FAST_FORWARD FOR
        SELECT
          code_bimar,
          name,
		  famil
        FROM bimaran
        WHERE transferred=0 or transferred is null
		order by code_bimar
    
        OPEN cursor_bimaran
        FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil

        WHILE @@FETCH_STATUS = 0
        BEGIN


		if not exists (select chart from [TSFD].[dbo].[injek]  where  chart=@code_bimar )
begin

  insert [TSFD].[dbo].[injek] 
  (
   chart
   ,oldchart
   ,name
  )
 values (@code_bimar,@code_bimar,@name+' '+@famil)

 end	

     if @@ROWCOUNT=1 
	 begin
	  update bimaran set transferred=1 where code_bimar=@code_bimar
	  set @patint_number_transferred=@patint_number_transferred+1
	 end


  
         FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil
        END
        CLOSE cursor_bimaran
        DEALLOCATE cursor_bimaran

       

end
select @patint_number_transferred as s_result , 'Number Of Inserted='+STR(@patint_number_transferred) +' with sp  ' as s_mesage ,'param ' as s_param
end

-- exec transfer_all_bimaran_to_Easydent4_injek
-- set primery key for injek
-- alter table [TSFD].[dbo].[injek]
-- alter callom  	[name] [nvarchar](64) NOT NULL,

-- select * from [TSFD].[dbo].[injek] order by chart DESC

-- select count(*) as tedad from [TSFD].[dbo].[injek]

-- delete  [TSFD].[dbo].[injek]
-- update bimaran set transferred=1  
-- update bimaran set transferred=0 where code_bimar < 20
-- select * from bimaran  where code_bimar < 100
-- select COUNT(*) from bimaran where transferred=1
-- select * from test_table order by id DESC


/*

-- delete  [TSFD].[dbo].[injek]
-- update bimaran set transferred=0
-- update bimaran set name='00'  where name is null
-- update bimaran set famil='00'  where famil is null
  insert into [TSFD].[dbo].[injek]
  (
   chart
   ,oldchart
   ,name
  )
 (select 
 code_bimar as chart 
 ,code_bimar as oldchart
 ,name+' '+famil as name from bimaran 
  where (LTRIM(RTRIM(famil))<> '')  and (transferred=0 or transferred is null) )



*/
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Scanora_PIDB_Patient_insert' AND type = 'P')
	 begin
	 set @old_name='sp_Scanora_PIDB_Patient_insert'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Scanora_PIDB_Patient_insert',@old_name;
   end
Go

create procedure [dbo].[sp_Scanora_PIDB_Patient_insert]
(
   @code_bimar varchar(10)
  ,@name nvarchar(50)
  ,@famil nvarchar(50)
  ,@sh_bimeh nvarchar(50)
  ,@picture_directory nvarchar(200)
)
as
begin

  set @code_bimar=ltrim(rtrim(@code_bimar))
  set @name=ltrim(rtrim(@name))
  set @famil=ltrim(rtrim(@famil))
  set @picture_directory=ltrim(rtrim(@picture_directory))
  if len(@picture_directory)=0
  set @picture_directory='c:\mycam'
 
  if (LEN(@code_bimar)>0 ) and (LEN(@name)+LEN(@famil)> 2) 
  begin
  
 if not exists (select PatientID from Scanora.dbo.PIDB_Patient   where PatientID=@code_bimar )
begin 
     insert into Scanora.dbo.PIDB_Patient 
                (PatientGUID, PatientID, 
                 FirstName, LastName,
                  MediaSubDirectory, ThirdPartySwID, 
                  MiddleInitials) values(str(@code_bimar)+'_P',@code_bimar,@name,@famil,@picture_directory,@sh_bimeh,@code_bimar)
end	
else
select '0' as s_resault,'Duplicate @code_bimar or  PatientID  in Table Scanora.dbo.PIDB_Patient  '
end
end

-- exec sp_Scanora_PIDB_Patient_insert  666,'Ali','Chamani','sh_bimeh','d:\mycam'

-- select * from Scanora.dbo.PIDB_Patient order by PatientID DESC

/*

*/
GO


declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Scanora_PIDB_Patient_insert_with_lock' AND type = 'P')
	 begin
	 set @old_name='sp_Scanora_PIDB_Patient_insert_with_lock'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Scanora_PIDB_Patient_insert_with_lock',@old_name;
   end
Go

create procedure [dbo].[sp_Scanora_PIDB_Patient_insert_with_lock]
(
-- run first to add field lock
-- ALTER TABLE Scanora.dbo.PIDB_Patient
-- ADD  [lock] [bit] NOT NULL 

   @code_bimar varchar(10)
  ,@name nvarchar(50)
  ,@famil nvarchar(50)
  ,@sh_bimeh nvarchar(50)
  ,@picture_directory nvarchar(200)
)
as
begin

  set @code_bimar=ltrim(rtrim(@code_bimar))
  set @name=ltrim(rtrim(@name))
  set @famil=ltrim(rtrim(@famil))
  set @picture_directory=ltrim(rtrim(@picture_directory))
  if len(@picture_directory)=0
  set @picture_directory='c:\mycam'
 
  if (LEN(@code_bimar)>0 ) and (LEN(@name)+LEN(@famil)> 2) 
  begin
  
 if not exists (select PatientID from Scanora.dbo.PIDB_Patient   where PatientID=@code_bimar )
begin 
     insert into Scanora.dbo.PIDB_Patient 
                (PatientGUID, PatientID, 
                 FirstName, LastName,
                 MediaSubDirectory, ThirdPartySwID, 
                 MiddleInitials,lock) values(str(@code_bimar)+'_P',@code_bimar,@name,@famil,@picture_directory,@sh_bimeh,@code_bimar,'1')
end	
else
select '0' as s_resault,'Duplicate @code_bimar or  PatientID  in Table Scanora.dbo.PIDB_Patient  '
end
end

-- exec sp_Scanora_PIDB_Patient_insert_with_lock  5,'Ali','Chamani','sh_bimeh','d:\mycam'

-- select PatientGUID, PatientID, FirstName, LastName,MediaSubDirectory, ThirdPartySwID, MiddleInitials,lock from Scanora.dbo.PIDB_Patient order by PatientID DESC

-- delete Scanora.dbo.PIDB_Patient

-- ALTER TABLE Scanora.dbo.PIDB_Patient
--  ADD  [lock] [bit] NOT NULL 
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_all_bimaran_to_Scanora_PIDB_Patient_insert_with_Lock' AND type = 'P')
	 begin
	 set @old_name='transfer_all_bimaran_to_Scanora_PIDB_Patient_insert_with_Lock'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_all_bimaran_to_Scanora_PIDB_Patient_insert_with_Lock',@old_name;
   end
Go

GO
create procedure [dbo].[transfer_all_bimaran_to_Scanora_PIDB_Patient_insert_with_Lock]
/*

-- run first to add field lock
-- ALTER TABLE Scanora.dbo.PIDB_Patient
-- ADD  [lock] [bit] NOT NULL 

*/
as
begin

DECLARE @code_bimar int
DECLARE @name nvarchar(50)
DECLARE @famil nvarchar(50)
DECLARE @sh_bimeh nvarchar(50)
DECLARE @picture_directory nvarchar(200)

set @picture_directory='c:\mycam'

DECLARE @number_transferred int=0

if exists (SELECT top 1
          code_bimar
        FROM bimaran
        WHERE transferred=0 or transferred is null)
begin
        DECLARE cursor_bimaran CURSOR FAST_FORWARD FOR
        SELECT
          code_bimar,
          name,
		  famil,
		  sh_bimeh
        FROM bimaran
        WHERE transferred=0 or transferred is null
		order by code_bimar
    
        OPEN cursor_bimaran
        FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil,@sh_bimeh

        WHILE @@FETCH_STATUS = 0
        BEGIN

 if not exists (select PatientID from Scanora.dbo.PIDB_Patient   where PatientID=@code_bimar )
begin 
     insert into Scanora.dbo.PIDB_Patient 
                (PatientGUID, PatientID, 
                 FirstName, LastName,
                 MediaSubDirectory, ThirdPartySwID, 
                 MiddleInitials,lock) values(str(@code_bimar)+'_P',@code_bimar,@name,@famil,@picture_directory,@sh_bimeh,@code_bimar,'1')

      if @@ROWCOUNT=1 
	  begin
	  update bimaran set transferred=1 where code_bimar=@code_bimar
	  set @number_transferred=@number_transferred+1
	 end
end	

  
         FETCH NEXT FROM cursor_bimaran INTO @code_bimar, @name,@famil,@sh_bimeh
        END
        CLOSE cursor_bimaran
        DEALLOCATE cursor_bimaran

       

end
select @number_transferred as s_result , 'Number Of Inserted='+STR(@number_transferred) +' with sp  '
end

-- exec transfer_all_bimaran_to_Scanora_PIDB_Patient_insert_with_Lock

-- exec sp_Scanora_PIDB_Patient_insert_with_lock  5,'Ali','Chamani','sh_bimeh','d:\mycam'

-- select PatientGUID, PatientID, FirstName, LastName,MediaSubDirectory, ThirdPartySwID, MiddleInitials,lock from Scanora.dbo.PIDB_Patient order by PatientID DESC

-- delete Scanora.dbo.PIDB_Patient

-- update bimaran set transferred=1

-- update bimaran set transferred=0 where code_bimar < 100

-- ALTER TABLE Scanora.dbo.PIDB_Patient
--  ADD  [lock] [bit] NOT NULL 


/*
-- delete  [TSFD].[dbo].[injek]
-- update bimaran set transferred=0
-- update bimaran set name='00'  where name is null
-- update bimaran set famil='00'  where famil is null
  insert into [TSFD].[dbo].[injek]
  (
   chart
   ,oldchart
   ,name
  )
 (select 
 code_bimar as chart 
 ,code_bimar as oldchart
 ,name+' '+famil as name from bimaran 
  where (LTRIM(RTRIM(famil))<> '')  and (transferred=0 or transferred is null) )



*/
Go


-- 1398/08/28

-- Vorod_Daro
ALTER TABLE [dbo].[Vorod_Daro]
    add [code_bakhsh] int Null
Go
ALTER TABLE [dbo].[Vorod_Daro]
    add [ID_Anbar_Hdr] int Null
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_anbar_itm_to_Vorod_Daro' AND type = 'P')
	 begin
	 set @old_name='transfer_anbar_itm_to_Vorod_Daro'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_anbar_itm_to_Vorod_Daro',@old_name;
   end
Go
create procedure [dbo].[transfer_anbar_itm_to_Vorod_Daro]
(
 @ID_Anbar_Hdr varchar(10)
, @code_bakhsh varchar(10)
)
as
begin

set  @ID_Anbar_Hdr=LTRIM(RTRIM(@ID_Anbar_Hdr)) 
set  @code_bakhsh=LTRIM(RTRIM(@code_bakhsh)) 

DECLARE @code_kala_Anbar_Itm int
DECLARE @qout_Anbar_Itm int
DECLARE @tarikh_Anbar_Itm char(10)

DECLARE @number_transferred int =0


if (exists (SELECT top 1
          Code_Kala
        FROM Anbar_Itm
        WHERE ID_Anbar_Hdr=@ID_Anbar_Hdr)) and (not exists(select top 1 id  from vorod_daro where ID_Anbar_Hdr=@ID_Anbar_Hdr) )
begin
        DECLARE cursor_Anbar_Itm CURSOR FAST_FORWARD FOR
        SELECT
          code_kala,
	      qout,
		  tarikh
        FROM Anbar_Itm
        WHERE ID_Anbar_Hdr=@ID_Anbar_Hdr
		order by radif
    
        OPEN cursor_Anbar_Itm
        FETCH NEXT FROM cursor_Anbar_Itm INTO @code_kala_Anbar_Itm, @qout_Anbar_Itm,@tarikh_Anbar_Itm

        WHILE @@FETCH_STATUS = 0
        BEGIN
		
  insert vorod_daro 
  (
   Tarikh,
  Code_Ertebat,
  Tedad,
  code_bakhsh,
  exp_tarikh,
  Sharh,
  ID_Anbar_Hdr
  )
 values (@tarikh_Anbar_Itm,@code_kala_Anbar_Itm,@qout_Anbar_Itm,@code_bakhsh,@tarikh_Anbar_Itm,' from  khoroj kala ID_Anbar_Hdr='+str(@ID_Anbar_Hdr),@ID_Anbar_Hdr)
 

     if @@ROWCOUNT=1  set @number_transferred=@number_transferred+1
	
  
         FETCH NEXT FROM cursor_Anbar_Itm INTO @code_kala_Anbar_Itm, @qout_Anbar_Itm,@tarikh_Anbar_Itm
        END
        CLOSE cursor_Anbar_Itm
        DEALLOCATE cursor_Anbar_Itm

       
select @number_transferred as s_result , '  Number Of record transferred='+RTRIM(LTRIM(STR(@number_transferred))) +' with sp :  '+OBJECT_NAME(@@PROCID) as s_message
end
else
select 0 as s_result , ' no condition for Anbar_Itm table or vorod_daro  to run sp :  '+OBJECT_NAME(@@PROCID) as s_message

end

-- exec transfer_anbar_itm_to_Vorod_Daro 145,12
-- select * from Anbar_Hdr order by ID_Anbar_Hdr DESC
-- select * from Anbar_Itm where ID_Anbar_Hdr=145
-- delete vorod_daro
-- select * from vorod_daro


Go



-- 1398/08/30

ALTER TABLE [dbo].[Anbar]
    add [active] bit Null
Go
update Anbar set active=1 where active is Null
Go
ALTER TABLE [dbo].[Anbar_itm]
    add [ID_Anbar_Hdr_tarnsfer] int Null
Go
ALTER TABLE [dbo].[Anbar_hdr]
    add [ID_Anbar_Hdr_tarnsfer] int Null
Go

insert Anbar(Code_Anber,Name_Anbar,active) values (2,N' انبار 2 ',1)
Go
insert Anbar(Code_Anber,Name_Anbar,active) values (3,N' انبار 3 ',1)
Go
insert Anbar(Code_Anber,Name_Anbar,active) values (4,N' انبار 4 ',1)
Go
insert Anbar(Code_Anber,Name_Anbar,active) values (5,N' انبار 5 ',1)
Go

ALTER TABLE [dbo].[bakhshha]
    add [code_anbar] int Null
Go
Update bakhshha set code_anbar=0 where code_anbar is null
Go
ALTER TABLE [dbo].[bakhshha]
    add [Code_Tafzil] char(10) Null
Go
Update bakhshha set Code_Tafzil='10001' where  Code_Tafzil  is null
Go

GO



declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_anbar_itm_to_selected_anbar' AND type = 'P')
	 begin
	 set @old_name='transfer_anbar_itm_to_selected_anbar'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_anbar_itm_to_selected_anbar',@old_name;
   end
Go

create procedure [dbo].[transfer_anbar_itm_to_selected_anbar]
-- by alich  13980902-1733
(
  @ID_Anbar_Hdr varchar(10)
, @code_anbar varchar(10)
, @code_user_insert varchar(10)
, @code_tafzil char(10)
, @code_noa_anbar varchar(10)
, @tarikh char(10) 
)
as
begin

DECLARE @radif_anbar_itm int
DECLARE @code_kala_Anbar_Itm int
DECLARE @code_unit_anbar_itm int
DECLARE @qout_Anbar_Itm int
DECLARE @tarikh_Anbar_Itm nvarchar(10)
DECLARE @fi_Anbar_Itm int
DECLARE @jam_Anbar_Itm int




DECLARE @number_transferred int =0
DECLARE @max_ID_Anbar_Hdr int =0


if (exists (SELECT top 1
          Code_Kala
        FROM Anbar_Itm
        WHERE ID_Anbar_Hdr=@ID_Anbar_Hdr)) and (not exists(select top 1 ID_Anbar_Hdr  from Anbar_Itm where ID_Anbar_Hdr_tarnsfer=@ID_Anbar_Hdr) )
begin


		           if exists(select top 1 ID_Anbar_Hdr from Anbar_Hdr  )
		           SELECT
                   @max_ID_Anbar_Hdr = MAX(ID_Anbar_Hdr)+1
                   FROM Anbar_Hdr
			       else set @max_ID_Anbar_Hdr=1

				   INSERT Anbar_Hdr (ID_Anbar_Hdr, Num_Anbar_Hdr,tarikh,Code_Anbar, Code_Tafzil, Code_Noa_Anbar, Code_User_Insert,Insert_Time, Jam, Ezaf, Kasr, Kol, Sharh,ID_Anbar_Hdr_tarnsfer)
        		   VALUES (@max_ID_Anbar_Hdr, 0,@tarikh,@Code_Anbar,@Code_Tafzil,@Code_Noa_Anbar, @code_user_insert, GETDATE(),0, 0, 0, 0,' enteghal anbar id='+LTRIM(@ID_Anbar_Hdr)+' '+[dbo].[Fn_Now_DateTime](),@ID_Anbar_Hdr)
                    
					 if @@ROWCOUNT=1  set @number_transferred=@number_transferred+1


        DECLARE cursor_Anbar_Itm CURSOR FAST_FORWARD FOR
         SELECT
          code_kala,
	      qout,
		  tarikh,
		  radif,
		  fi,
		  Jam
        FROM Anbar_Itm
        WHERE ID_Anbar_Hdr=@ID_Anbar_Hdr
		order by radif

         OPEN cursor_Anbar_Itm
       FETCH NEXT FROM cursor_Anbar_Itm INTO @code_kala_Anbar_Itm, @qout_Anbar_Itm,@tarikh_Anbar_Itm,@radif_anbar_itm,@fi_Anbar_Itm,@jam_Anbar_Itm
        WHILE @@FETCH_STATUS = 0
        BEGIN
		
              INSERT Anbar_Itm (ID_Anbar_Hdr,Num_Anbar_Hdr, Code_Tafzil, Code_Noa_Anbar, Code_Anbar, Tarikh, Radif, Code_Kala, code_unit, kardex, qin, qout, Fi, Jam, sharh, Code_User_Insert, Insert_Time,ID_Anbar_Hdr_tarnsfer)
               VALUES (@max_ID_Anbar_Hdr,0,@Code_Tafzil,@Code_Noa_Anbar,@Code_Anbar, @tarikh,1, @code_kala_Anbar_Itm, @code_unit_anbar_itm,@qout_Anbar_Itm,@qout_Anbar_Itm,0 ,@fi_Anbar_Itm,@jam_Anbar_Itm,' enteghal anbar id='+LTRIM(@ID_Anbar_Hdr)+' '+[dbo].[Fn_Now_DateTime]() , @code_user_insert, GETDATE(),@ID_Anbar_Hdr)
               if @@ROWCOUNT=1  set @number_transferred=@number_transferred+1
	
  
         FETCH NEXT FROM cursor_Anbar_Itm INTO @code_kala_Anbar_Itm, @qout_Anbar_Itm,@tarikh_Anbar_Itm,@radif_anbar_itm,@fi_Anbar_Itm,@jam_Anbar_Itm
        END
        CLOSE cursor_Anbar_Itm
        DEALLOCATE cursor_Anbar_Itm

       

select @number_transferred as s_result , 'Number of record transferrd='+LTRIM(STR(@number_transferred)) +' with sp: '+OBJECT_NAME(@@PROCID)  as s_message
end
else
select 0 as s_result , ' no record anbar_item or tansfer done before  '  as s_message

end

/*

--   EXEC transfer_anbar_itm_to_selected_anbar 146,2,2,'2222',1,'1398/08/30'
--   SELECT * FROM ANBAR_HDR order by ID_Anbar_Hdr DESC
--   SELECT * FROM ANBAR_itm where  ID_Anbar_Hdr=146  order by radif
--   SELECT top 100 * FROM ANBAR_itm order by ID_Anbar_Itm

*/


Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'Fn_Now_DateTime' AND type = 'FN')
	 begin
	 set @old_name='Fn_Now_DateTime'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'Fn_Now_DateTime',@old_name;
   end
Go
Create  FUNCTION [dbo].[Fn_Now_DateTime]
()
RETURNS char(14)
AS
BEGIN
    DECLARE @Result char(14)='';
	
	DECLARE @md  datetime
	
	set @md=GETDATE()

	set @Result=LTRIM(DATEPART(YEAR, @md))+LTRIM(DATEPART(MONTH, @md))+LTRIM(DATEPART(DAY, @md))+
    LTRIM(DATEPART(HOUR,@md))+LTRIM(DATEPART(MINUTE, @md))+LTRIM(DATEPART(SECOND, @md))  

	RETURN RTRIM(LTRIM(@Result))

end

/*
--  select  [dbo].[Fn_Now_DateTime]()
*/
Go

IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_havale_khoroj_kala_pakage_koli')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N' حواله خروج  اتوماتیک درمانهای دارای تعریف پکیج از پذیرش  ', 'sp_havale_khoroj_kala_pakage_koli', 'sp_havale_khoroj_kala_pakage_koli.fr3', 1, 'sp_parameters', 1,1)
END
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_havale_khoroj_kala_pakage_koli' AND type = 'P')
	 begin
	 set @old_name='sp_havale_khoroj_kala_pakage_koli'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_havale_khoroj_kala_pakage_koli',@old_name;
   end
Go
create PROCEDURE [dbo].[sp_havale_khoroj_kala_pakage_koli] (
-- sp_havale_khoroj_kala_pakage_koli by alich 1398/09/02
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10),
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),
@code_ertebat varchar(10),
@code_shift_str varchar(5000),
@code_bimeh_str varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),
@code_mokammel varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10))
AS
  -- از بین بردن فضای خالی
  SET @from_tarikh = LTRIM(RTRIM(@from_tarikh));
  SET @to_tarikh = LTRIM(RTRIM(@to_tarikh));
  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @code_darman = LTRIM(RTRIM(@code_darman));
  SET @code_shift = LTRIM(RTRIM(@code_shift));
  SET @code_user_insert = LTRIM(RTRIM(@code_user_insert));
  SET @code_pay = LTRIM(RTRIM(@code_pay));
  SET @code_shobeh = LTRIM(RTRIM(@code_shobeh));
  SET @from_time = LTRIM(RTRIM(@from_time));
  SET @to_time = LTRIM(RTRIM(@to_time));
  SET @sh_kargozini = LTRIM(RTRIM(@sh_kargozini));
  SET @code_ertebat = LTRIM(RTRIM(@code_ertebat));
  SET @code_shift_str = LTRIM(RTRIM(@code_shift_str));
  SET @code_bimeh_str = LTRIM(RTRIM(@code_bimeh_str));
  SET @code_bakhsh_str = LTRIM(RTRIM(@code_bakhsh_str));
  SET @code_pezeshk_str = LTRIM(RTRIM(@code_pezeshk_str));
  SET @code_yaraneh = LTRIM(RTRIM(@code_yaraneh));
  SET @code_mokammel = LTRIM(RTRIM(@code_mokammel));
  SET @code_dastyar = LTRIM(RTRIM(@code_dastyar));
  SET @code_ranandeh = LTRIM(RTRIM(@code_ranandeh));

  DECLARE @s_mess nvarchar(4000)='';

  BEGIN
 
    set @s_mess=@s_mess+' @from_tarikh='+@from_tarikh
	set @s_mess=@s_mess+' @to_tarikh='+@to_tarikh
	set @s_mess=@s_mess+' @code_user_insert='+@code_user_insert
	set @s_mess=@s_mess+' @code_shift='+@code_shift

    IF ((LEN(@from_tarikh) = 10)
      AND (LEN(@to_tarikh) = 10)
      AND (@code_user_insert > 0)
      AND (@code_shift > 0))
	  BEGIN
      IF EXISTS (SELECT
          code_morajeh
        FROM morajeat
        WHERE tarikh BETWEEN @from_tarikh AND @to_tarikh
        AND code_user_insert = @code_user_insert
        AND code_shift = code_shift
        AND ID_Anbar_Hdr < 1
        AND code_darman IN (SELECT
          code_darman
        FROM Anbar_Itm_Set_Masraf_Darman
        GROUP BY code_darman))
      BEGIN

	    DECLARE @Code_Tafzil char(10)
		select @Code_Tafzil=Code_Tafzil_Masraf_Daro from setting

        DECLARE @Code_Anbar int
		select @Code_Anbar=Code_Anbar_Masraf_Daro from setting
	

		DECLARE @Code_Noa_Anbar int=2
        DECLARE @code_morajeh int
        DECLARE @tarikh_morajeh char(10)
		DECLARE @code_darman_morajeh int
		DECLARE @code_bimar_morajeh int
        DECLARE @code_pezeshk_morajeh int
        DECLARE @tedad_darman_morajeh int
		DECLARE @code_bakhsh_morajeh int
		DECLARE @code_anbar_bakhsh_morajeh int
		DECLARE @code_tafzil_bakhsh_morajeh int

        DECLARE @radif_masraf int
        DECLARE @Code_Kala_masraf int
        DECLARE @Code_Uni_masraft int
        DECLARE @qout_masraf int
        DECLARE @fi_masraf int
        DECLARE @Jam_masraf int
        DECLARE @max_ID_Anbar_Hdr int
		DECLARE @Anbar_Hdr_inserted int=0
		DECLARE @Anbar_itm_inserted int=0

        DECLARE cursor_morajeat CURSOR FAST_FORWARD FOR
        SELECT
          code_morajeh,
          tarikh,
		  code_bimar,
		  code_pezeshk,
          code_darman,
          tedad_darman,
		  code_bakhsh
        FROM morajeat
        WHERE tarikh BETWEEN @from_tarikh AND @to_tarikh
        AND code_user_insert = @code_user_insert
        AND code_shift = code_shift
        AND ID_Anbar_Hdr < 1
        ORDER BY code_morajeh DESC

        OPEN cursor_morajeat
        FETCH NEXT FROM cursor_morajeat INTO @code_morajeh, @tarikh_morajeh,@code_bimar_morajeh,@code_pezeshk_morajeh,@code_darman_morajeh, @tedad_darman_morajeh,@code_bakhsh_morajeh
		select @code_anbar_bakhsh_morajeh=code_anbar,@code_tafzil_bakhsh_morajeh=code_tafzil from bakhshha where code_bakhsh=@code_bakhsh_morajeh

        -- loop 
        WHILE @@FETCH_STATUS = 0
        BEGIN
          IF EXISTS (SELECT
              Code_Kala
            FROM Anbar_Itm_Set_Masraf_Darman
            WHERE code_darman = @code_darman_morajeh)
          BEGIN

                    if exists(select top 1 ID_Anbar_Hdr from Anbar_Hdr  )
		           SELECT
                   @max_ID_Anbar_Hdr = MAX(ID_Anbar_Hdr)+1
                   FROM Anbar_Hdr
			       else set @max_ID_Anbar_Hdr=1


            INSERT Anbar_Hdr (ID_Anbar_Hdr, Num_Anbar_Hdr,tarikh,Code_Anbar, Code_Tafzil, Code_Noa_Anbar, Code_User_Insert,Insert_Time, Jam, Ezaf, Kasr, Kol, Sharh)
              VALUES (@max_ID_Anbar_Hdr, 0,@tarikh_morajeh,@code_anbar_bakhsh_morajeh,@code_tafzil_bakhsh_morajeh,@Code_Noa_Anbar, @code_user_insert, GETDATE(),0, 0, 0, 0, @tarikh_morajeh+'  code_bimar='+LTRIM(STR(@code_bimar_morajeh))+'  code_pezeshk='+LTRIM(STR(@code_pezeshk_morajeh))+'  code_morajeh='+LTRIM(STR(@code_morajeh)))
           
            if @@ROWCOUNT=1
		    update morajeat set ID_Anbar_Hdr=@max_ID_Anbar_Hdr where code_morajeh=@code_morajeh

			set @Anbar_Hdr_inserted=@Anbar_Hdr_inserted+1

            DECLARE cursor_masraf CURSOR FAST_FORWARD FOR
            SELECT
              radif,
              Code_Kala,
              Code_Unit,
              qout,
              fi,
              Jam
            FROM Anbar_Itm_Set_Masraf_Darman
            WHERE code_darman = @code_darman_morajeh

            OPEN cursor_masraf
            FETCH NEXT FROM cursor_masraf INTO @radif_masraf, @Code_Kala_masraf, @Code_Uni_masraft, @qout_masraf, @fi_masraf, @Jam_masraf
            WHILE @@FETCH_STATUS = 0
            BEGIN

              INSERT Anbar_Itm (ID_Anbar_Hdr,Num_Anbar_Hdr, Code_Tafzil, Code_Noa_Anbar, Code_Anbar, Tarikh, Radif, Code_Kala, code_unit, kardex, qin, qout, Fi, Jam, sharh, Code_User_Insert, Insert_Time)
               VALUES (@max_ID_Anbar_Hdr,0,@code_tafzil_bakhsh_morajeh,@Code_Noa_Anbar,@code_anbar_bakhsh_morajeh, @tarikh_morajeh, @radif_masraf, @Code_Kala_masraf, @Code_Uni_masraft, 1, 0, @qout_masraf, @fi_masraf, @Jam_masraf,@tarikh_morajeh+'  code_bimar='+LTRIM(STR(@code_bimar_morajeh))+'  code_pezeshk='+LTRIM(STR(@code_pezeshk_morajeh))+'  code_morajeh='+LTRIM(STR(@code_morajeh)), @code_user_insert, GETDATE())

                set @Anbar_itm_inserted=@Anbar_itm_inserted+1 

              FETCH NEXT FROM cursor_masraf INTO @radif_masraf, @Code_Kala_masraf, @Code_Uni_masraft, @qout_masraf, @fi_masraf, @Jam_masraf
            END

            CLOSE cursor_masraf
            DEALLOCATE cursor_masraf
          END
          -- end inner loop

          FETCH NEXT FROM cursor_morajeat INTO @code_morajeh, @tarikh_morajeh,@code_bimar_morajeh,@code_pezeshk_morajeh,@code_darman_morajeh, @tedad_darman_morajeh,@code_bakhsh_morajeh
		  select @code_anbar_bakhsh_morajeh=code_anbar,@code_tafzil_bakhsh_morajeh=code_tafzil from bakhshha where code_bakhsh=@code_bakhsh_morajeh
        END
        CLOSE cursor_morajeat
        DEALLOCATE cursor_morajeat
      -- end outter loop
	            SELECT
          @Anbar_Hdr_inserted+@Anbar_itm_inserted AS s_result,
          'Number of Inserted to Anbar_Hdr,Anbar_itm  with :   ' + OBJECT_NAME(@@PROCID)+' '+str(@Anbar_Hdr_inserted)+' '+str(@Anbar_itm_inserted) AS s_message,
		   @s_mess as s_param 
         END
		 ELSE
		 SELECT
          '0' AS s_result,
          'no record in table morajeat  stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 

      END
      ELSE
        SELECT
          '0' AS s_result,
          'no coddition to run stored procedure :   ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_mess as s_param 
  END

  -- exec sp_havale_khoroj_kala_pakage_koli_alich13980902 '1398/09/01','1398/09/04','','','','','',1,14,'','','','','','','','','','','','','',''
  -- delete Anbar_Hdr
  -- delete anbar_itm
  -- update morajeat set ID_Anbar_Hdr=0 ,code_user_insert=14, code_shift=1
  -- update morajeat set tarikh='1398/01/01' where tarikh > '1398/08/26'
  -- update moshtari set tahvil_girandeh_kala=1 , foroshande_kala=1
  /*
  SELECT  tarikh,code_morajeh,code_darman,
    	  code_user_insert,code_shift
        FROM morajeat  where
		 code_darman in (select code_darman from Anbar_Itm_Set_Masraf_Darman group by code_darman )
		 order by tarikh
  */

-- select * from anbar_hdr
-- select * from anbar_itm
-- SELECT * from Noa_Anbar
-- SELECT * from Anbar_Itm_Set_Masraf_Darman
-- select code_morajeh,tarikh,ID_Anbar_Hdr from morajeat order by  ID_Anbar_Hdr DESC

Go



IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_report_nemodar_hozor_be_saat')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N'  نمودار حضور به ساعت   ', 'sp_report_nemodar_hozor_be_saat', 'sp_report_nemodar_hozor_be_saat.fr3', 1, 'sp_parameters', 1,1)
END
Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_report_nemodar_hozor_be_saat' AND type = 'P')
	 begin
	 set @old_name='sp_report_nemodar_hozor_be_saat'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_report_nemodar_hozor_be_saat',@old_name;
   end
Go
create PROCEDURE [dbo].[sp_report_nemodar_hozor_be_saat](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));
set @code_ranandeh=LTRIM(RTRIM(@code_ranandeh));

  

BEGIN
     -- select LTRIM(DATEPART(HOUR,insert_time)),COUNT(*) from morajeat  group by LTRIM(DATEPART(HOUR,insert_time)) order by LTRIM(DATEPART(HOUR,insert_time))
     -- select DATEPART(HOUR,insert_time) as Saat ,COUNT(*) as Tedad , sum(r_bes) as pardakhti  from morajeat  group by DATEPART(HOUR,insert_time) order by DATEPART(HOUR,insert_time)

    DECLARE @s_param nvarchar(4000)='';
    set @s_param=@s_param+' @from_tarikh='+@from_tarikh
	set @s_param=@s_param+' @to_tarikh='+@to_tarikh

 if ((len(@from_tarikh)=10)and (len(@to_tarikh)=10))
 begin

 select DATEPART(HOUR,insert_time) as Saat ,
 COUNT(*) as Tedad 
 from morajeat  
 where tarikh between @from_tarikh and @to_tarikh
 group by DATEPART(HOUR,insert_time) 
 order by DATEPART(HOUR,insert_time)

 end
 else
 select 
          '0' AS s_result,
          ':( no condition to run sp : ' + OBJECT_NAME(@@PROCID) AS s_message,
		   @s_param as s_param 
END
-- exec sp_report_nemodar_hozor_be_saat '1390/09/01','1399/09/01','','','','','','','','','','','','','','','','','','','','',''
Go

CREATE TABLE Pictures (
   pictureName NVARCHAR(40) PRIMARY KEY NOT NULL
   , picFileName NVARCHAR (100)
   , PictureData VARBINARY (max)
   )
GO
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'usp_ImportImage' AND type = 'P')
	 begin
	 set @old_name='usp_ImportImage'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'usp_ImportImage',@old_name;
   end
Go
CREATE PROCEDURE dbo.usp_ImportImage (
     @PicName NVARCHAR (100)
   , @ImageFolderPath NVARCHAR (1000)
   , @Filename NVARCHAR (1000)
   )
AS
-- Simple Image Import and Export Using T-SQL for SQL Server
-- exec dbo.usp_ImportImage 'DRAGON','C:\MyPictures\Input','Dragon.jpg' 
-- exec dbo.usp_ExportImage 'DRAGON','C:\MyPictures\Output','Dragon.jpg' 

BEGIN
   DECLARE @Path2OutFile NVARCHAR (2000);
   DECLARE @tsql NVARCHAR (2000);
   SET NOCOUNT ON
   SET @Path2OutFile = CONCAT (
         @ImageFolderPath
         ,'\'
         , @Filename
         );
   SET @tsql = 'insert into Pictures (pictureName, picFileName, PictureData) ' +
               ' SELECT ' + '''' + @PicName + '''' + ',' + '''' + @Filename + '''' + ', * ' + 
               'FROM Openrowset( Bulk ' + '''' + @Path2OutFile + '''' + ', Single_Blob) as img'
   EXEC (@tsql)
   SET NOCOUNT OFF
END
GO

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'usp_ExportImage' AND type = 'P')
	 begin
	 set @old_name='usp_ExportImage'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'usp_ExportImage',@old_name;
   end
Go
CREATE PROCEDURE dbo.usp_ExportImage (
   @PicName NVARCHAR (100)
   ,@ImageFolderPath NVARCHAR(1000)
   ,@Filename NVARCHAR(1000)
   )
AS
-- Simple Image Import and Export Using T-SQL for SQL Server
-- exec dbo.usp_ImportImage 'DRAGON','C:\MyPictures\Input','Dragon.jpg' 
-- exec dbo.usp_ExportImage 'DRAGON','C:\MyPictures\Output','Dragon.jpg' 

BEGIN
   DECLARE @ImageData VARBINARY (max);
   DECLARE @Path2OutFile NVARCHAR (2000);
   DECLARE @Obj INT
 
   SET NOCOUNT ON
 
   SELECT @ImageData = (
         SELECT convert (VARBINARY (max), PictureData, 1)
         FROM Pictures
         WHERE pictureName = @PicName
         );
 
   SET @Path2OutFile = CONCAT (
         @ImageFolderPath
         ,'\'
         , @Filename
         );
    BEGIN TRY
     EXEC sp_OACreate 'ADODB.Stream' ,@Obj OUTPUT;
     EXEC sp_OASetProperty @Obj ,'Type',1;
     EXEC sp_OAMethod @Obj,'Open';
     EXEC sp_OAMethod @Obj,'Write', NULL, @ImageData;
     EXEC sp_OAMethod @Obj,'SaveToFile', NULL, @Path2OutFile, 2;
     EXEC sp_OAMethod @Obj,'Close';
     EXEC sp_OADestroy @Obj;
    END TRY
    
 BEGIN CATCH
  EXEC sp_OADestroy @Obj;
 END CATCH
 
   SET NOCOUNT OFF
END
GO

-- exec dbo.usp_ImportImage 'DRAGON','C:\MyPictures\Input','Dragon.jpg' 
-- exec dbo.usp_ExportImage 'DRAGON','C:\MyPictures\Output','Dragon.jpg' 
Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'Drop_30_Old_Procedure_And_Function' AND type = 'P')
	 begin
	 set @old_name='Drop_30_Old_Procedure_And_Function'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'Drop_30_Old_Procedure_And_Function',@old_name;
   end

Go
create procedure Drop_30_Old_Procedure_And_Function
as
begin

declare @object_name_like varchar(200)='%_old_2019%' 
declare @name_sysobjects sysname
declare @type_sysobjects char(2)
declare @deleted_object int=0
declare @sqlst varchar(1000)='' 
DECLARE	@return_value int

if exists (SELECT top 1 name FROM sysobjects
      WHERE (name like @object_name_like ) AND (type = 'P' or type = 'FN'))
begin
        DECLARE cursor_sysobjects CURSOR FAST_FORWARD FOR
        SELECT top 30 
          name,
		  type
        FROM sysobjects
        WHERE (name like @object_name_like ) AND (type = 'P' or type = 'FN')

        OPEN cursor_sysobjects
        FETCH NEXT FROM cursor_sysobjects INTO @name_sysobjects,@type_sysobjects

        WHILE @@FETCH_STATUS = 0
        BEGIN


		if  exists (SELECT name FROM sysobjects where name=@name_sysobjects and [type]='P')
        begin
	    	
		   set @sqlst=' DROP PROCEDURE '+ @name_sysobjects
	       exec (@sqlst)
		   set @deleted_object=@deleted_object+1
		   --exec @return_value=@sqlst
		   --set @deleted_object=@deleted_object+@return_value
        end	
		
     
		if  exists (SELECT name FROM sysobjects where name=@name_sysobjects and [type]='FN')
        begin
		   set @sqlst=' DROP FUNCTION '+ @name_sysobjects
  		   exec (@sqlst)
		   set @deleted_object=@deleted_object+1
		--   exec @return_value=@sqlst
		--   set @deleted_object=@deleted_object+@return_value
        end	
		
  
         FETCH NEXT FROM cursor_sysobjects INTO @name_sysobjects,@type_sysobjects
        END
		
        CLOSE cursor_sysobjects
        DEALLOCATE cursor_sysobjects

        select @deleted_object as s_result,' Number of sysobjects deleted='+ltrim(@deleted_object) as s_message
		
end
else
     select '0' as s_result,'no record found in table sysobjects with condition  '+ @object_name_like as s_message

end
Go

/*
-- exec Drop_30_Old_Procedure_And_Function

declare @object_name_like varchar(200)='%_old_2019%' 
SELECT  name FROM sysobjects
 WHERE (name like @object_name_like ) AND (type = 'P' or type = 'FN')

*/
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'Fn_FileExists' AND type = 'FN')
	 begin
	 set @old_name='Fn_FileExists'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'Fn_FileExists',@old_name;
   end

Go
create FUNCTION dbo.Fn_FileExists(@path varchar(8000))  
RETURNS BIT  
AS  
BEGIN  
     DECLARE @result INT  
     EXEC master.dbo.xp_fileexist @path, @result OUTPUT  
     RETURN cast(@result as bit)  
END
/*
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

*/

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_ImportImage_to_NeedSoft_Bimaran_Image' AND type = 'P')
	 begin
	 set @old_name='sp_ImportImage_to_NeedSoft_Bimaran_Image'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_ImportImage_to_NeedSoft_Bimaran_Image',@old_name;
   end

Go
create  PROCEDURE [dbo].[sp_ImportImage_to_NeedSoft_Bimaran_Image] (
     @code_bimar int
    ,@Fpath NVARCHAR (2000)
   )
AS
BEGIN

   DECLARE @tsql NVARCHAR (2000);
   SET NOCOUNT ON

   SET @tsql = 'insert into bimaran_image (code_bimar, tarikh,sharh,insert_time, image_bimar) ' +
               ' SELECT ' + '''' + LTRIM(@code_bimar) + '''' + ',' + '''' +dbo.GregorianToPersian(convert(varchar, getdate(), 111)) + '''' + ',' + '''' + ' transferd with sp ' + '''' +',' + '''' + convert(varchar, getdate(), 25) + '''' + ', * ' + 
                'FROM Openrowset( Bulk ' + '''' +@Fpath + '''' + ', Single_Blob) as img'
   --select @tsql
   EXEC (@tsql)
   SET NOCOUNT OFF
END

Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Ezdenti_e2_img_ExportImage' AND type = 'P')
	 begin
	 set @old_name='sp_Ezdenti_e2_img_ExportImage'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Ezdenti_e2_img_ExportImage',@old_name;
   end

Go


create PROCEDURE [dbo].[sp_Ezdenti_e2_img_ExportImage]
AS
BEGIN
  IF EXISTS (SELECT TOP 1
      img_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL))
  BEGIN
    
	DECLARE @mpath varchar(300) = 'C:\MyPictures'
	select @mpath=path_imge_Ezdenti from Setting_Ezdenti where id=1
	
	DECLARE @path_Bmp2Jpeg varchar(300)
	select @path_Bmp2Jpeg=path_imge_Ezdenti from Setting_Ezdenti where id=1
	


    DECLARE @spath varchar(300) = ''-- subfolders
    DECLARE @spath_list TABLE (
      subdirectory varchar(255),
      depth int,
      [file] bit
    )
    DECLARE @fpath varchar(8000) = ''-- final file&path 
    DECLARE @file_count_transferd int = 0
    DECLARE @img_id_e2_img int
    DECLARE @img_filename_e2_img varchar(200)
    DECLARE @pat_id_e2_img int

    DECLARE cursor_e2_img CURSOR FAST_FORWARD FOR
    SELECT TOP 30
      img_id,
      img_filename,
      pat_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL)
    OPEN cursor_e2_img
    FETCH NEXT FROM cursor_e2_img INTO @img_id_e2_img, @img_filename_e2_img, @pat_id_e2_img
    WHILE @@FETCH_STATUS = 0
    BEGIN
      -- crate table s from subfolders of main path  
      INSERT INTO @spath_list EXEC xp_dirtree @mpath,
                                              1,
                                              1
      -- select * from  @spath_list

      DECLARE cursor_spath_list CURSOR FAST_FORWARD FOR
      SELECT
        subdirectory
      FROM @spath_list
      WHERE depth = 1
      AND [file] = 0
      OPEN cursor_spath_list
      FETCH NEXT FROM cursor_spath_list INTO @spath
      WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @fpath = @mpath + '\' + @spath + '\' + @img_filename_e2_img
        IF ([dbo].[FA_FileExists](@fpath) = 1)
        BEGIN
		  
		  if substring(@fpath,(LEN(@fpath)-2),3)='bmp'
		  begin
		  set @path_Bmp2Jpeg=@path_Bmp2Jpeg+' '+@fpath
		  EXEC xp_cmdshell @path_Bmp2Jpeg
		  set @fpath=substring(@fpath,1,(LEN(@fpath)-3))+'jpg'
          end

          EXEC sp_ImportImage_to_NeedSoft_Bimaran_Image @pat_id_e2_img,
                                                        @fpath
		 SET @file_count_transferd = @file_count_transferd + 1
        -- if @@ROWCOUNT=1
        -- update [SQLAuth_PG].[E2].[public].[e2_img] set transfered=1
        --select @fpath
        END
        FETCH NEXT FROM cursor_spath_list INTO @spath
      END
      CLOSE cursor_spath_list
      DEALLOCATE cursor_spath_list

      FETCH NEXT FROM cursor_e2_img INTO @img_id_e2_img, @img_filename_e2_img, @pat_id_e2_img
    END
    CLOSE cursor_e2_img
    DEALLOCATE cursor_e2_img

    SELECT
      @file_count_transferd AS s_result,
      ':)  Record count transferdfrom table e2_img to new table  ' + LTRIM(@file_count_transferd) AS s_message

  END
  ELSE
    SELECT
      -1 AS s_result,
      ':( No record in table e2_img to transfer  ' AS s_message
END
--  exec sp_Ezdenti_e2_img_ExportImage

/*

select * from [sqlauth_pg].[E2].[public].[e2_pat]

-- person on EZdenti

select 
pat_id,
pat_chartno,
pat_lastname,
pat_firstname,
pat_middlename 
from [sqlauth_pg].[E2].[public].[e2_pat]


SELECT [img_id]
      ,[img_filename]

      ,[pat_id]
	  ,[transferd]
  FROM [SQLAuth_PG].[E2].[public].[e2_img]



--  select * from [sqlauth_pg].[E2].[public].[e2_img]



declare @files table (subdirectory varchar(255),depth int , [file] bit )
declare @main_path varchar(300)
set @main_path='C:\MyPictures'
insert into @files EXEC xp_dirtree  @main_path,6, 1
select * from @files





EXEC xp_dirtree 'C:\', 2, 1


Rename file using MS sql server(xp_cmdshell), 
GetAllFileDetails in MS SqlServer (xp_getfiledetails)

 xp_getfiledetails

'DateCreated' - Return Created date of file.
'DateLastAccessed' - Return Last access date of file.
'DateLastModified' - Return Last modified date of file.
'Drive' - Return file located drive name.
'Name' - Return name of file.
'ParentFolder' - Return parent folder of file.
'Path' -  Return path of file.
'ShortPath' - Returnshort path of file.
'Size' - Return size of file.
'Type'  - Return Type of file(.txt,.doc,etc...)
xp_cmdshell




--Declare variables holding properties of file
DECLARE @Attributes TINYINT,
@DateCreated DATETIME,
@DateLastAccessed DATETIME,
@DateLastModified DATETIME,
@Drive VARCHAR(1),
@Name NVARCHAR(255),
@ParentFolder NVARCHAR(255),
@Path NVARCHAR(255),
@ShortPath NVARCHAR(255),
@Size INT,
@Type NVARCHAR(255)

--Get properties of fileobject
EXEC sp_OAGetProperty @fileobj, 'Attributes', @Attributes OUT
EXEC sp_OAGetProperty @fileobj, 'DateCreated', @DateCreated OUT
EXEC sp_OAGetProperty @fileobj, 'DateLastAccessed', @DateLastAccessed OUT
EXEC sp_OAGetProperty @fileobj, 'DateLastModified', @DateLastModified OUT
EXEC sp_OAGetProperty @fileobj, 'Drive', @Drive OUT
EXEC sp_OAGetProperty @fileobj, 'Name', @Name OUT
EXEC sp_OAGetProperty @fileobj, 'ParentFolder', @ParentFolder OUT
EXEC sp_OAGetProperty @fileobj, 'Path', @Path OUT
EXEC sp_OAGetProperty @fileobj, 'ShortPath', @ShortPath OUT
EXEC sp_OAGetProperty @fileobj, 'Size', @Size OUT
EXEC sp_OAGetProperty @fileobj, 'Type', @Type OUT





image path
C:\Program Files(x86)\VATECH\Common\FM\FMData\Files

EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE

declare @files table (ID int IDENTITY, FileName varchar(100))
insert into @files execute xp_cmdshell 'dir c:\ /b'
select * from @files

declare @files table (ID int IDENTITY, FileName varchar(1000))
insert into @files execute xp_cmdshell 'dir C:\Program Files(x86)\VATECH\Common\FM\FMData\Files\ /b'
select * from @files



 field transfered (bit) add to e2_img

ALTER TABLE [sqlauth_pg].[E2].[public].[e2_img]
    add [transfered] bit Null
Go

Alter  Table  e2_img  
Add  transfered bit Null

select * from [sqlauth_pg].[E2].[public].[e2_pat]

-- person on EZdenti

select 
pat_id,
pat_chartno,
pat_lastname,
pat_firstname,
pat_middlename 
from [sqlauth_pg].[E2].[public].[e2_pat]


--  select * from [sqlauth_pg].[E2].[public].[e2_img]

SELECT [img_id]
      ,[img_filename]
      ,[img_modality]
      ,[img_mode]
      ,[img_acquisition_datetime]
      ,[img_imported]
      ,[img_kvp]
      ,[img_ma]
      ,[img_dose]
      ,[img_note]
      ,[pat_id]
      ,[pat_chartno]
      ,[img_raw_filename]
      ,[img_update_datetime]
      ,[img_modelname]
      ,[img_study_instance_uid]
      ,[rec_id]
  FROM [SQLAuth_PG].[E2].[public].[e2_img]



How to check File is Exist or Not in Directory using T-SQL

DECLARE @output INT

EXEC @output = XP_CMDSHELL 'DIR "E:\temp\TextTest.txt" /B', NO_OUTPUT

IF @output = 1

      PRINT 'File Donot exists'

ELSE

      PRINT 'File exists'




CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\FolderName"'

IF EXISTS (SELECT * FROM #TEMP WHERE FileList LIKE '%Name of File%')
BEGIN
	Your code
END





If you do decide to use xp_fileexist, you have to make sure the SQL Server service account 
has access to the directory where you will be looking for files.

DECLARE @iFileExists INT

EXEC master..xp_fileexist 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\test.txt', 
 @iFileExists OUTPUT

SELECT @iFileExists

If you are using xp_cmdshell, i recommend that you use /B to get only the file/directory name. (Thanks to Dbp2784 for the sample script).  Again the SQL Server Service accounts needs access to the file or directory.

CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\test.txt" /B', NO_OUTPUT

IF EXISTS (SELECT * FROM #TEMP WHERE FileList = 'test.txt')
BEGIN
	SELECT 1
END




You will have to do this using extended stored procedure xp_cmdshell

CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\FolderName"'

IF EXISTS (SELECT * FROM #TEMP WHERE FileList LIKE '%Name of File%')
BEGIN
	Your code
END




    DECLARE @output INT

    EXEC @output = XP_CMDSHELL 'DIR "E:\temp\TextTest.txt" /B', NO_OUTPUT

    IF @output = 1

          PRINT 'File Donot exists'

    ELSE

          PRINT 'File exists'

     

Declare @cmdShellCommand varchar(400) = 'DIR "' + @BackupDirectory +'" /B'  

EXEC @output = XP_CMDSHELL @cmdShellCommand, NO_OUTPUT

--  

EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE

declare @files table (ID int IDENTITY, FileName varchar(100))
insert into @files execute xp_cmdshell 'dir c:\ /b'
select * from @files


---

DECLARE @TEMP TABLE (OUTPUT NVARCHAR(500))

INSERT INTO @TEMP
EXEC XP_CMDSHELL 'DIR [C:\MyPictures] /B /S /A:-D'

UPDATE @TEMP
SET OUTPUT = REPLACE(OUTPUT,'[C:\MyPictures]','')

SELECT PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),3) AS SUB1 
, PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),2) AS SUB2 
, PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),1) + '.xls' AS SUB3 
FROM @TEMP
WHERE OUTPUT LIKE '%.XLS'



EXEC xp_dirtree 'C:\', 1, 1
      

*/

-- EXEC xp_dirtree 'C:\MyPictures',6, 1



-- declare @files table (ID int IDENTITY, FileName varchar(100))
-- insert into @files execute xp_cmdshell 'dir C:\MyPictures /b'
-- select * from @files
Go
-------------------------------------------------------------------
Go
CREATE FUNCTION [dbo].[GregorianToPersian]
(
    @Date varchar(10)
)
RETURNS varchar(10)
AS
BEGIN

    DECLARE @ResultVar varchar(10)

    declare @Year int
    declare @Month int
    declare @Day int
    declare @PersianYear int
    declare @PersianMonth int
    declare @PersianDay int
    declare @StartMonthGregorianDateInPersianCalendar int=10
    declare @StartDayGregorianDateInPersianCalendar int=11

    set @Year=convert(int,substring(@Date,1,4))
    set @Month=convert(int,substring(@Date,6,2))
    set @Day=convert(int,substring(@Date,9,2))
    declare @GregorianDayIndex int=0
   
 if(dbo.IsLeapYear(@Year)=1)
        set @StartDayGregorianDateInPersianCalendar=11
    else
        if(dbo.IsLeapYear(@Year-1)=1)
            set @StartDayGregorianDateInPersianCalendar=12
        else
            set @StartDayGregorianDateInPersianCalendar=11
          declare @m_index int=1
    while @m_index<=@Month-1
    begin
        set @GregorianDayIndex=@GregorianDayIndex+dbo.NumberOfDaysInMonthGregorian(@Year,@m_index)
        set @m_index=@m_index+1
    end
    set @GregorianDayIndex=@GregorianDayIndex+@Day

    if(@GregorianDayIndex>=80)
    begin
        set @PersianYear=@Year-621
    end
    else
    begin
        set @PersianYear=@Year-622
    end

    declare @mdays int
    declare @m int
    declare @index int=@GregorianDayIndex
    set @m_index=0
    while 1=1
    begin
        if(@m_index<=2)
            set @m=@StartMonthGregorianDateInPersianCalendar+@m_index
        else
            set @m=@m_index-2

        set @mdays=dbo.NumberOfDayInMonthPersian(@Year,@m)
        if(@m=@StartMonthGregorianDateInPersianCalendar)
            set @mdays=@mdays-@StartDayGregorianDateInPersianCalendar+1
       
        if(@index<=@mdays)
        begin
            set @PersianMonth=@m
            if(@m=@StartMonthGregorianDateInPersianCalendar)
                set @PersianDay=@index+@StartDayGregorianDateInPersianCalendar-1
            else
                set @PersianDay=@index
            break
        end
        else
        begin
            set @index=@index-@mdays
            set @m_index=@m_index+1
        end           
    end

    set @ResultVar=
    convert(varchar(4),@PersianYear)+'/'+
    right('0'+convert(varchar(2),@PersianMonth),2)+'/'+
    right('0'+convert(varchar(2),@PersianDay),2)

    -- Return the result of the function
    RETURN @ResultVar

END

GO
------------------------------------------------------------------
Go
create FUNCTION [dbo].[IsLeapYear]
(
    @Year int
)
RETURNS bit
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar bit

    -- Add the T-SQL statements to compute the return value here
    if @Year % 400 = 0
       Begin
            set @ResultVar=1
       end
    else if @Year % 100 = 0
       Begin
            set @ResultVar=0
       end
    else if @Year % 4 = 0
       Begin
            set @ResultVar=1
       end
    else
       Begin
            set @ResultVar=0
       end

    -- Return the result of the function
    RETURN @ResultVar

END

GO
-------------------------------------------
create FUNCTION [dbo].[NumberOfDayInMonthPersian]
(
    @Year int,-- Gregorian Year
    @Month int -- Presian Month
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar int

    -- Add the T-SQL statements to compute the return value here
    if(@Month<=6)
        set @ResultVar=31
    else
        if(@Month=12)
            if(dbo.IsLeapYear(@Year-1)=1)
                set @ResultVar=30
            else
                set @ResultVar=29
        else
            set @ResultVar=30

    -- Return the result of the function
    RETURN @ResultVar

END

GO
-------------------------------------------------------------
Go
create FUNCTION [dbo].[NumberOfDaysInMonthGregorian]
(
    @Year int
    ,@Month int
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar int

    -- Add the T-SQL statements to compute the return value here
    if(@Month<>2)
    begin
        set @ResultVar=30+((@Month + FLOOR(@Month/8)) % 2)
    end
    else
    begin
        if(dbo.IsLeapYear(@Year)=1)
        begin
            set @ResultVar=29
        end
        else
        begin
            set @ResultVar=28
        end
    end

    -- Return the result of the function
    RETURN @ResultVar

END

GO
---------------------------------------------------------------
Go
create FUNCTION [dbo].[PersianToGregorian](@DateStr varchar(10))
RETURNS DATE
AS  
BEGIN 
   declare @YYear int
   declare @MMonth int
   declare @DDay int
   declare @epbase int
   declare @epyear int
   declare @mdays int
   declare @persian_jdn int
   declare @i int
   declare @j int
   declare @l int
   declare @n int
   declare @TMPRESULT varchar(10)
   declare @IsValideDate int
   declare @TempStr varchar(20)
   DECLARE @TmpDateStr varchar(10)

   SET @i=charindex('/',@DateStr)

   IF LEN(@DateStr) - CHARINDEX('/', @DateStr,CHARINDEX('/', @DateStr,1)+1) = 4
   BEGIN
   --  SET @TmpDateStr = dbo.ReversDate(@DateStr)
     IF ( ISDATE(@TmpDateStr) =1 )  
       RETURN @TmpDateStr
     ELSE
        RETURN NULL
   END
   ELSE
     SET @TmpDateStr = @DateStr

   IF ((@i<>0) and
     --  (dbo.SubStrCount('/', @TmpDateStr)=2) and
        (ISNUMERIC(REPLACE(@TmpDateStr,'/',''))=1) and 
        (charindex('.',@TmpDateStr)=0)
       )
   BEGIN
       SET @YYear=CAST(SUBSTRING(@TmpDateStr,1,@i-1) AS INT)
                IF ( @YYear< 1300 )
                      SET @YYear =@YYear + 1300
                IF @YYear > 9999
                  RETURN NULL
    
       SET @TempStr= SUBSTRING(@TmpDateStr,@i+1,Len(@TmpDateStr))
    
       SET @i=charindex('/',@TempStr)
       SET @MMonth=CAST(SUBSTRING(@TempStr,1,@i-1) AS INT)
       SET @MMonth=@MMonth-- -1
       
       SET @TempStr= SUBSTRING(@TempStr,@i+1,Len(@TempStr))   
    
       SET @DDay=CAST(@TempStr AS INT)
       SET @DDay=@DDay-- - 1
           
                 IF ( @YYear >= 0 )
                     SET @epbase = @YYear - 474
                 Else
                     SET @epbase = @YYear - 473
                 SET @epyear = 474 + (@epbase % 2820)

        IF (@MMonth <= 7 )
                       SET @mdays = ((@MMonth) - 1) * 31
        Else
            SET @mdays = ((@MMonth) - 1) * 30 + 6

        SET @persian_jdn =(@DDay)  + @mdays + CAST((((@epyear * 682) - 110) / 2816) as int)  + (@epyear - 1) * 365  +  CAST((@epbase / 2820)  as int ) * 1029983  + (1948321 - 1)

        IF (@persian_jdn > 2299160) 
                 BEGIN
            SET @l = @persian_jdn + 68569
            SET @n = CAST(((4 * @l) / 146097) as int)
            SET @l = @l -  CAST(((146097 * @n + 3) / 4) as int)
            SET @i =  CAST(((4000 * (@l + 1)) / 1461001) as int)
            SET @l = @l - CAST( ((1461 * @i) / 4) as int) + 31
            SET @j =  CAST(((80 * @l) / 2447) as int)
            SET @DDay = @l - CAST( ((2447 * @j) / 80) as int)
             SET @l =  CAST((@j / 11) as int)
            SET @MMonth = @j + 2 - 12 * @l
            SET @YYear = 100 * (@n - 49) + @i + @l
                 END

           SET @TMPRESULT=Cast(@MMonth as varchar(2))+'/'+CAST(@DDay as Varchar(2))+'/'+CAST(@YYear as varchar(4))  
           RETURN Cast(@TMPRESULT as varchar(10))

    END
    RETURN NULL      

END

GO
-------------------------------------------------------------------------
GO
CREATE FUNCTION [dbo].[FA_FileExists](@path varchar(8000))  
RETURNS BIT  
AS  
BEGIN  
     DECLARE @result INT  
     EXEC master.dbo.xp_fileexist @path, @result OUTPUT  
     RETURN cast(@result as bit)  
END
/*
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

*/

GO

CREATE TABLE [dbo].[Setting_Ezdenti](
	[id] [int] NOT NULL,
	[path_imge_Ezdenti] [varchar](300) NULL,
	[path_Bmp2Jpeg] [varchar](300) NULL,
 CONSTRAINT [PK_Setting_Ezdenti] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
insert Setting_Ezdenti (id,path_imge_Ezdenti,path_Bmp2Jpeg) values (1,'C:\MyPictures','C:\MyPictures\Bmp2Jpeg.exe')
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Ezdenti_e2_img_ExportImage_all' AND type = 'P')
	 begin
	 set @old_name='sp_Ezdenti_e2_img_ExportImage_all'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Ezdenti_e2_img_ExportImage_all',@old_name;
   end

Go

create PROCEDURE [dbo].[sp_Ezdenti_e2_img_ExportImage_all]
AS
BEGIN
/*
--  by alich needsoft  1398/09/05

--  exec sp_Ezdenti_e2_img_ExportImage_all

not install Ezden servor on program file

set D:\VATECH\EzDentFile\

check intrnal sp result hatman

set param path_imge_Ezdenti,path_imge_Ezdenti  Setting_Ezdenti
select * from Setting_Ezdenti

update Setting_Ezdenti 
set path_Bmp2Jpeg='C:\VATECH20\Common\FM\FMData\Files\Bmp2Jpeg.exe',
path_imge_Ezdenti='C:\VATECH20\Common\FM\FMData\Files'


EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
-- test 
EXEC xp_dirtree 'C:\', 1, 1

*/

  IF EXISTS (SELECT TOP 1
      img_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL))
  BEGIN

    DECLARE @Trace_SP bit=0
	set @Trace_SP=1
    
	DECLARE @mpath varchar(300) = 'C:\MyPictures'
	select @mpath=path_imge_Ezdenti from Setting_Ezdenti where id=1
	
	DECLARE @path_Bmp2Jpeg varchar(300)
	select @path_Bmp2Jpeg=path_Bmp2Jpeg from Setting_Ezdenti where id=1
	DECLARE @path_param_Bmp2Jpeg varchar(300)=''

    DECLARE @spath varchar(300) = ''-- subfolders
    DECLARE @spath_list TABLE (
      subdirectory varchar(255),
      depth int,
      [file] bit
    )
    DECLARE @fpath varchar(8000) = ''-- final file&path 
    DECLARE @file_count_transferd int = 0
    DECLARE @img_id_e2_img int
    DECLARE @img_filename_e2_img varchar(200)
    DECLARE @pat_id_e2_img int

    DECLARE cursor_e2_img CURSOR FAST_FORWARD FOR
    SELECT TOP 30
      img_id,
      img_filename,
      pat_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL) order by img_id DESC
    OPEN cursor_e2_img
    FETCH NEXT FROM cursor_e2_img INTO @img_id_e2_img, @img_filename_e2_img, @pat_id_e2_img
    WHILE @@FETCH_STATUS = 0
    BEGIN
      -- crate table s from subfolders of main path  
      INSERT INTO @spath_list EXEC xp_dirtree @mpath,
                                              1,
                                              1
      -- select * from  @spath_list

      DECLARE cursor_spath_list CURSOR FAST_FORWARD FOR
      SELECT
        subdirectory
      FROM @spath_list
      WHERE depth = 1
      AND [file] = 0
      OPEN cursor_spath_list
      FETCH NEXT FROM cursor_spath_list INTO @spath
      WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @fpath = @mpath + '\' + @spath + '\' + @img_filename_e2_img
        IF ([dbo].[FA_FileExists](@fpath) = 1)
        BEGIN
		  
		  if substring(@fpath,(LEN(@fpath)-2),3)='bmp'
		  begin
		  set @path_param_Bmp2Jpeg=@path_Bmp2Jpeg+' '+@fpath
		  EXEC xp_cmdshell @path_param_Bmp2Jpeg
		  set @fpath=substring(@fpath,1,(LEN(@fpath)-3))+'jpg'
          end

          EXEC sp_ImportImage_to_NeedSoft_Bimaran_Image @pat_id_e2_img,
                                                        @fpath
		 
         update [SQLAuth_PG].[E2].[public].[e2_img] set transfered=1 where img_id=@img_id_e2_img

		 SET @file_count_transferd = @file_count_transferd + 1

        END
        FETCH NEXT FROM cursor_spath_list INTO @spath
      END
      CLOSE cursor_spath_list
      DEALLOCATE cursor_spath_list

      FETCH NEXT FROM cursor_e2_img INTO @img_id_e2_img, @img_filename_e2_img, @pat_id_e2_img
    END
    CLOSE cursor_e2_img
    DEALLOCATE cursor_e2_img

    SELECT
      @file_count_transferd AS s_result,
      ':)  Record count transferdfrom table e2_img to new table  ' + LTRIM(@file_count_transferd)+'  with param '+@mpath+' '+@path_Bmp2Jpeg AS s_message,'param' as s_param 

  END
  ELSE
    SELECT
      -1 AS s_result,
      ':( No record in table e2_img to transfer conditin  WHERE (transfered = 0)  OR (transfered IS NULL)) ' AS s_message ,'param' as s_param 
END
Go
--  exec sp_Ezdenti_e2_img_ExportImage_all
ALTER TABLE [dbo].[bimaran_image]
   ADD  [transferd_img_id] [int] NULL  
Go
ALTER TABLE [dbo].[bimaran_image]
   ADD  [transferd_filename] nvarchar(100) NULL  
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_job_Ezdenti_e2_img_GetImage' AND type = 'P')
	 begin
	 set @old_name='sp_job_Ezdenti_e2_img_GetImage'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_job_Ezdenti_e2_img_GetImage',@old_name;
   end

Go

create PROCEDURE [dbo].[sp_job_Ezdenti_e2_img_GetImage]
AS
BEGIN
/*
--   by alich needsoft  1398/09/05

--  exec sp_job_Ezdenti_e2_img_GetImage

at first chechk link server to allow sp to create
add field transferd as integer to e2_img to allow sp to create

run Sql Shell to change pas postgres
\password
username postgres
password 123

run a program to likne server
trial PGNP-Postgres-SE-Trial-1.4.0.3566-x64
Copyright © 2006-2014 Intellisoft LLC
All rights reserved.

rest windows  to take efect aftre change pass and alter table


run script to  create linke serve

/*

EXEC MASTER.dbo.sp_MSset_oledb_prop N'PGNP'  ,N'AllowInProcess',1
GO
EXEC MASTER.dbo.sp_MSset_oledb_prop N'PGNP'  ,N'DynamicParameters',1
GO
DECLARE @name NVARCHAR(4000);
DECLARE @provider NVARCHAR(4000);
DECLARE @servername NVARCHAR(4000);
DECLARE @port NVARCHAR(4000);
DECLARE @db_name NVARCHAR(4000)
-- destination postgres database
SET @name = N'SQLAuth_PG';
SET @provider = N'PGNP';
SET @servername = N'localhost';
SET @port = 'PORT=5432;'
SET @db_name = N'E2';
-- create linked server
EXEC MASTER.dbo.sp_addlinkedserver @server = @name
,@srvproduct = N'PGNP'
,@provider = N'PGNP'
,@datasrc = @servername
,@provstr = @port
,@catalog = @db_name
-- username and password for postgres
EXEC MASTER.dbo.sp_addlinkedsrvlogin @rmtsrvname = @name
,@useself = N'False'
,@locallogin = NULL
,@rmtuser = N'postgres'
,@rmtpassword = '123'
-- set up Extended properties of the Linked Server
EXEC MASTER.dbo.sp_serveroption @server = @name
,@optname = 'data access'
,@optvalue = 'true'
EXEC MASTER.dbo.sp_serveroption @server = @name
,@optname = 'use remote collation'
,@optvalue = 'true'
EXEC MASTER.dbo.sp_serveroption @server = @name
,@optname = 'rpc'
,@optvalue = 'true'
EXEC MASTER.dbo.sp_serveroption @server = @name
,@optname = 'rpc out'
,@optvalue = 'true'
GO


---select * from [sqlauth_pg].[E2].[public].[e2_pat]

---INSERT INTO [SQLAuth_PG].[E2].[public].[e2_pat]
           ([pat_id]
           ,[pat_chartno]
           ,[pat_lastname]
           ,[pat_firstname]
         )
     VALUES

	 (
	 1,
	 '11',
	 'jj',
	 'aa'

      )    
GO

*/

check

SELECT TOP 1
      img_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL)

rest windows 

not install Ezden servor on program file

set D:\VATECH\EzDentFile\

check intrnal sp result hatman

set param path_imge_Ezdenti,path_imge_Ezdenti  Setting_Ezdenti
select * from Setting_Ezdenti

update Setting_Ezdenti 
set path_Bmp2Jpeg='C:\VATECH20\Common\FM\FMData\Files\Bmp2Jpeg.exe',
path_imge_Ezdenti='C:\VATECH20\Common\FM\FMData\Files'


EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
-- test 
EXEC xp_dirtree 'C:\', 1, 1

Use master
Go
EXEC sp_configure 'show advanced options', 1; 
GO 
RECONFIGURE; 
GO 
EXEC sp_configure 'Ole Automation Procedures', 1; 
GO 
RECONFIGURE; 
GO
--ALTER SERVER ROLE [bulkadmin] ADD MEMBER [Enter here the Login Name that will execute the Import] 
--ALTER SERVER ROLE [bulkadmin] ADD MEMBER [sa] 
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [acp\Administrator] 
GO  


*/

  IF EXISTS (SELECT TOP 1
      img_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL))
  BEGIN

    DECLARE @Trace_SP bit=0
	set @Trace_SP=1
    
	DECLARE @mpath varchar(300) = 'C:\MyPictures'
	select @mpath=path_imge_Ezdenti from Setting_Ezdenti where id=1
	
	DECLARE @path_Bmp2Jpeg varchar(300)
	select @path_Bmp2Jpeg=path_Bmp2Jpeg from Setting_Ezdenti where id=1
	DECLARE @path_param_Bmp2Jpeg varchar(300)=''

    DECLARE @spath varchar(300) = ''-- subfolders
    DECLARE @spath_list TABLE (
      subdirectory varchar(255),
      depth int,
      [file] bit
    )
    DECLARE @fpath varchar(8000) = ''-- final file&path 
    DECLARE @file_count_transferd int = 0
    DECLARE @img_id_e2_img int
    DECLARE @img_filename_e2_img varchar(200)
    DECLARE @pat_id_e2_img int

    DECLARE cursor_e2_img CURSOR FAST_FORWARD FOR
    SELECT TOP 30
      img_id,
      img_filename,
      pat_id
    FROM [SQLAuth_PG].[E2].[public].[e2_img]
    WHERE (transfered = 0)
    OR (transfered IS NULL) order by img_id DESC
    OPEN cursor_e2_img
    FETCH NEXT FROM cursor_e2_img INTO @img_id_e2_img, @img_filename_e2_img, @pat_id_e2_img
    WHILE @@FETCH_STATUS = 0
    BEGIN
      -- crate table s from subfolders of main path  
      INSERT INTO @spath_list EXEC xp_dirtree @mpath,
                                              1,
                                              1
      -- select * from  @spath_list

      DECLARE cursor_spath_list CURSOR FAST_FORWARD FOR
      SELECT
        subdirectory
      FROM @spath_list
      WHERE depth = 1
      AND [file] = 0
      OPEN cursor_spath_list
      FETCH NEXT FROM cursor_spath_list INTO @spath
      WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @fpath = @mpath + '\' + @spath + '\' + @img_filename_e2_img
        IF ([dbo].[FA_FileExists](@fpath) = 1)
        BEGIN
		  
		  if substring(@fpath,(LEN(@fpath)-2),3)='bmp'
		  begin
		  set @path_param_Bmp2Jpeg=@path_Bmp2Jpeg+' '+@fpath
		  EXEC xp_cmdshell @path_param_Bmp2Jpeg
		  set @fpath=substring(@fpath,1,(LEN(@fpath)-3))+'jpg'
          end

          EXEC sp_Ezdenti_ExportImage_to_Bimaran_Image @img_id_e2_img,@img_filename_e2_img,@pat_id_e2_img,
                                                        @fpath

		 if EXISTS(select id from Bimaran_Image where transferd_img_id=@img_id_e2_img)
		 begin
         update [SQLAuth_PG].[E2].[public].[e2_img] set transfered=1 where img_id=@img_id_e2_img
		 SET @file_count_transferd = @file_count_transferd + 1
		 end

        END
        FETCH NEXT FROM cursor_spath_list INTO @spath
      END
      CLOSE cursor_spath_list
      DEALLOCATE cursor_spath_list

      FETCH NEXT FROM cursor_e2_img INTO @img_id_e2_img, @img_filename_e2_img, @pat_id_e2_img
    END
    CLOSE cursor_e2_img
    DEALLOCATE cursor_e2_img

    SELECT
      @file_count_transferd AS s_result,
      ':)  Record count transferdfrom table e2_img to new table  ' + LTRIM(@file_count_transferd)+'  with param '+@mpath+' '+@path_Bmp2Jpeg AS s_message 

  END
  ELSE
    SELECT
      -1 AS s_result,
      ':( No record in table e2_img to transfer conditin  WHERE (transfered = 0)  OR (transfered IS NULL)) ' AS s_message
END
--  exec sp_job_Ezdenti_e2_img_GetImage
/*

select * from [sqlauth_pg].[E2].[public].[e2_pat]

-- person on EZdenti

select 
pat_id,
pat_chartno,
pat_lastname,
pat_firstname,
pat_middlename 
from [sqlauth_pg].[E2].[public].[e2_pat]


SELECT [img_id]
      ,[img_filename]

      ,[pat_id]
	  ,[transferd]
  FROM [SQLAuth_PG].[E2].[public].[e2_img]



--  select * from [sqlauth_pg].[E2].[public].[e2_img]



declare @files table (subdirectory varchar(255),depth int , [file] bit )
declare @main_path varchar(300)
set @main_path='C:\MyPictures'
insert into @files EXEC xp_dirtree  @main_path,6, 1
select * from @files





EXEC xp_dirtree 'C:\', 2, 1


Rename file using MS sql server(xp_cmdshell), 
GetAllFileDetails in MS SqlServer (xp_getfiledetails)

 xp_getfiledetails

'DateCreated' - Return Created date of file.
'DateLastAccessed' - Return Last access date of file.
'DateLastModified' - Return Last modified date of file.
'Drive' - Return file located drive name.
'Name' - Return name of file.
'ParentFolder' - Return parent folder of file.
'Path' -  Return path of file.
'ShortPath' - Returnshort path of file.
'Size' - Return size of file.
'Type'  - Return Type of file(.txt,.doc,etc...)
xp_cmdshell




--Declare variables holding properties of file
DECLARE @Attributes TINYINT,
@DateCreated DATETIME,
@DateLastAccessed DATETIME,
@DateLastModified DATETIME,
@Drive VARCHAR(1),
@Name NVARCHAR(255),
@ParentFolder NVARCHAR(255),
@Path NVARCHAR(255),
@ShortPath NVARCHAR(255),
@Size INT,
@Type NVARCHAR(255)

--Get properties of fileobject
EXEC sp_OAGetProperty @fileobj, 'Attributes', @Attributes OUT
EXEC sp_OAGetProperty @fileobj, 'DateCreated', @DateCreated OUT
EXEC sp_OAGetProperty @fileobj, 'DateLastAccessed', @DateLastAccessed OUT
EXEC sp_OAGetProperty @fileobj, 'DateLastModified', @DateLastModified OUT
EXEC sp_OAGetProperty @fileobj, 'Drive', @Drive OUT
EXEC sp_OAGetProperty @fileobj, 'Name', @Name OUT
EXEC sp_OAGetProperty @fileobj, 'ParentFolder', @ParentFolder OUT
EXEC sp_OAGetProperty @fileobj, 'Path', @Path OUT
EXEC sp_OAGetProperty @fileobj, 'ShortPath', @ShortPath OUT
EXEC sp_OAGetProperty @fileobj, 'Size', @Size OUT
EXEC sp_OAGetProperty @fileobj, 'Type', @Type OUT





image path
C:\Program Files(x86)\VATECH\Common\FM\FMData\Files

EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE

declare @files table (ID int IDENTITY, FileName varchar(100))
insert into @files execute xp_cmdshell 'dir c:\ /b'
select * from @files

declare @files table (ID int IDENTITY, FileName varchar(1000))
insert into @files execute xp_cmdshell 'dir C:\Program Files(x86)\VATECH\Common\FM\FMData\Files\ /b'
select * from @files



 field transfered (bit) add to e2_img

ALTER TABLE [sqlauth_pg].[E2].[public].[e2_img]
    add [transfered] bit Null
Go

Alter  Table  e2_img  
Add  transfered bit Null

select * from [sqlauth_pg].[E2].[public].[e2_pat]

-- person on EZdenti

select 
pat_id,
pat_chartno,
pat_lastname,
pat_firstname,
pat_middlename 
from [sqlauth_pg].[E2].[public].[e2_pat]


--  select * from [sqlauth_pg].[E2].[public].[e2_img]

SELECT [img_id]
      ,[img_filename]
      ,[img_modality]
      ,[img_mode]
      ,[img_acquisition_datetime]
      ,[img_imported]
      ,[img_kvp]
      ,[img_ma]
      ,[img_dose]
      ,[img_note]
      ,[pat_id]
      ,[pat_chartno]
      ,[img_raw_filename]
      ,[img_update_datetime]
      ,[img_modelname]
      ,[img_study_instance_uid]
      ,[rec_id]
  FROM [SQLAuth_PG].[E2].[public].[e2_img]



How to check File is Exist or Not in Directory using T-SQL

DECLARE @output INT

EXEC @output = XP_CMDSHELL 'DIR "E:\temp\TextTest.txt" /B', NO_OUTPUT

IF @output = 1

      PRINT 'File Donot exists'

ELSE

      PRINT 'File exists'




CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\FolderName"'

IF EXISTS (SELECT * FROM #TEMP WHERE FileList LIKE '%Name of File%')
BEGIN
	Your code
END





If you do decide to use xp_fileexist, you have to make sure the SQL Server service account 
has access to the directory where you will be looking for files.

DECLARE @iFileExists INT

EXEC master..xp_fileexist 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\test.txt', 
 @iFileExists OUTPUT

SELECT @iFileExists

If you are using xp_cmdshell, i recommend that you use /B to get only the file/directory name. (Thanks to Dbp2784 for the sample script).  Again the SQL Server Service accounts needs access to the file or directory.

CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\test.txt" /B', NO_OUTPUT

IF EXISTS (SELECT * FROM #TEMP WHERE FileList = 'test.txt')
BEGIN
	SELECT 1
END




You will have to do this using extended stored procedure xp_cmdshell

CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\FolderName"'

IF EXISTS (SELECT * FROM #TEMP WHERE FileList LIKE '%Name of File%')
BEGIN
	Your code
END




    DECLARE @output INT

    EXEC @output = XP_CMDSHELL 'DIR "E:\temp\TextTest.txt" /B', NO_OUTPUT

    IF @output = 1

          PRINT 'File Donot exists'

    ELSE

          PRINT 'File exists'

     

Declare @cmdShellCommand varchar(400) = 'DIR "' + @BackupDirectory +'" /B'  

EXEC @output = XP_CMDSHELL @cmdShellCommand, NO_OUTPUT

--  

EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE

declare @files table (ID int IDENTITY, FileName varchar(100))
insert into @files execute xp_cmdshell 'dir c:\ /b'
select * from @files


---

DECLARE @TEMP TABLE (OUTPUT NVARCHAR(500))

INSERT INTO @TEMP
EXEC XP_CMDSHELL 'DIR [C:\MyPictures] /B /S /A:-D'

UPDATE @TEMP
SET OUTPUT = REPLACE(OUTPUT,'[C:\MyPictures]','')

SELECT PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),3) AS SUB1 
, PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),2) AS SUB2 
, PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),1) + '.xls' AS SUB3 
FROM @TEMP
WHERE OUTPUT LIKE '%.XLS'



EXEC xp_dirtree 'C:\', 1, 1
      

*/

-- EXEC xp_dirtree 'C:\MyPictures',6, 1



-- declare @files table (ID int IDENTITY, FileName varchar(100))
-- insert into @files execute xp_cmdshell 'dir C:\MyPictures /b'
-- select * from @files






/*

select * from [sqlauth_pg].[E2].[public].[e2_pat]

-- person on EZdenti

select 
pat_id,
pat_chartno,
pat_lastname,
pat_firstname,
pat_middlename 
from [sqlauth_pg].[E2].[public].[e2_pat]


SELECT [img_id]
      ,[img_filename]

      ,[pat_id]
	  ,[transferd]
  FROM [SQLAuth_PG].[E2].[public].[e2_img]



--  select * from [sqlauth_pg].[E2].[public].[e2_img]



declare @files table (subdirectory varchar(255),depth int , [file] bit )
declare @main_path varchar(300)
set @main_path='C:\MyPictures'
insert into @files EXEC xp_dirtree  @main_path,6, 1
select * from @files





EXEC xp_dirtree 'C:\', 2, 1


Rename file using MS sql server(xp_cmdshell), 
GetAllFileDetails in MS SqlServer (xp_getfiledetails)

 xp_getfiledetails

'DateCreated' - Return Created date of file.
'DateLastAccessed' - Return Last access date of file.
'DateLastModified' - Return Last modified date of file.
'Drive' - Return file located drive name.
'Name' - Return name of file.
'ParentFolder' - Return parent folder of file.
'Path' -  Return path of file.
'ShortPath' - Returnshort path of file.
'Size' - Return size of file.
'Type'  - Return Type of file(.txt,.doc,etc...)
xp_cmdshell




--Declare variables holding properties of file
DECLARE @Attributes TINYINT,
@DateCreated DATETIME,
@DateLastAccessed DATETIME,
@DateLastModified DATETIME,
@Drive VARCHAR(1),
@Name NVARCHAR(255),
@ParentFolder NVARCHAR(255),
@Path NVARCHAR(255),
@ShortPath NVARCHAR(255),
@Size INT,
@Type NVARCHAR(255)

--Get properties of fileobject
EXEC sp_OAGetProperty @fileobj, 'Attributes', @Attributes OUT
EXEC sp_OAGetProperty @fileobj, 'DateCreated', @DateCreated OUT
EXEC sp_OAGetProperty @fileobj, 'DateLastAccessed', @DateLastAccessed OUT
EXEC sp_OAGetProperty @fileobj, 'DateLastModified', @DateLastModified OUT
EXEC sp_OAGetProperty @fileobj, 'Drive', @Drive OUT
EXEC sp_OAGetProperty @fileobj, 'Name', @Name OUT
EXEC sp_OAGetProperty @fileobj, 'ParentFolder', @ParentFolder OUT
EXEC sp_OAGetProperty @fileobj, 'Path', @Path OUT
EXEC sp_OAGetProperty @fileobj, 'ShortPath', @ShortPath OUT
EXEC sp_OAGetProperty @fileobj, 'Size', @Size OUT
EXEC sp_OAGetProperty @fileobj, 'Type', @Type OUT





image path
C:\Program Files(x86)\VATECH\Common\FM\FMData\Files

EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE

declare @files table (ID int IDENTITY, FileName varchar(100))
insert into @files execute xp_cmdshell 'dir c:\ /b'
select * from @files

declare @files table (ID int IDENTITY, FileName varchar(1000))
insert into @files execute xp_cmdshell 'dir C:\Program Files(x86)\VATECH\Common\FM\FMData\Files\ /b'
select * from @files



 field transfered (bit) add to e2_img

ALTER TABLE [sqlauth_pg].[E2].[public].[e2_img]
    add [transfered] bit Null
Go

Alter  Table  e2_img  
Add  transfered bit Null

select * from [sqlauth_pg].[E2].[public].[e2_pat]

-- person on EZdenti

select 
pat_id,
pat_chartno,
pat_lastname,
pat_firstname,
pat_middlename 
from [sqlauth_pg].[E2].[public].[e2_pat]


--  select * from [sqlauth_pg].[E2].[public].[e2_img]

SELECT [img_id]
      ,[img_filename]
      ,[img_modality]
      ,[img_mode]
      ,[img_acquisition_datetime]
      ,[img_imported]
      ,[img_kvp]
      ,[img_ma]
      ,[img_dose]
      ,[img_note]
      ,[pat_id]
      ,[pat_chartno]
      ,[img_raw_filename]
      ,[img_update_datetime]
      ,[img_modelname]
      ,[img_study_instance_uid]
      ,[rec_id]
  FROM [SQLAuth_PG].[E2].[public].[e2_img]



How to check File is Exist or Not in Directory using T-SQL

DECLARE @output INT

EXEC @output = XP_CMDSHELL 'DIR "E:\temp\TextTest.txt" /B', NO_OUTPUT

IF @output = 1

      PRINT 'File Donot exists'

ELSE

      PRINT 'File exists'




CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\FolderName"'

IF EXISTS (SELECT * FROM #TEMP WHERE FileList LIKE '%Name of File%')
BEGIN
	Your code
END





If you do decide to use xp_fileexist, you have to make sure the SQL Server service account 
has access to the directory where you will be looking for files.

DECLARE @iFileExists INT

EXEC master..xp_fileexist 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\test.txt', 
 @iFileExists OUTPUT

SELECT @iFileExists

If you are using xp_cmdshell, i recommend that you use /B to get only the file/directory name. (Thanks to Dbp2784 for the sample script).  Again the SQL Server Service accounts needs access to the file or directory.

CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\test.txt" /B', NO_OUTPUT

IF EXISTS (SELECT * FROM #TEMP WHERE FileList = 'test.txt')
BEGIN
	SELECT 1
END




You will have to do this using extended stored procedure xp_cmdshell

CREATE TABLE #TEMP(FileList Varchar(MAX))

INSERT INTO #TEMP
EXEC XP_CMDSHELL 'DIR "C:\FolderName"'

IF EXISTS (SELECT * FROM #TEMP WHERE FileList LIKE '%Name of File%')
BEGIN
	Your code
END




    DECLARE @output INT

    EXEC @output = XP_CMDSHELL 'DIR "E:\temp\TextTest.txt" /B', NO_OUTPUT

    IF @output = 1

          PRINT 'File Donot exists'

    ELSE

          PRINT 'File exists'

     

Declare @cmdShellCommand varchar(400) = 'DIR "' + @BackupDirectory +'" /B'  

EXEC @output = XP_CMDSHELL @cmdShellCommand, NO_OUTPUT

--  

EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
-- this enables xp_cmdshell
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE

declare @files table (ID int IDENTITY, FileName varchar(100))
insert into @files execute xp_cmdshell 'dir c:\ /b'
select * from @files


---

DECLARE @TEMP TABLE (OUTPUT NVARCHAR(500))

INSERT INTO @TEMP
EXEC XP_CMDSHELL 'DIR [C:\MyPictures] /B /S /A:-D'

UPDATE @TEMP
SET OUTPUT = REPLACE(OUTPUT,'[C:\MyPictures]','')

SELECT PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),3) AS SUB1 
, PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),2) AS SUB2 
, PARSENAME(REPLACE(REPLACE(OUTPUT,'.XLS',''),'\','.'),1) + '.xls' AS SUB3 
FROM @TEMP
WHERE OUTPUT LIKE '%.XLS'



EXEC xp_dirtree 'C:\', 1, 1
      

*/

-- EXEC xp_dirtree 'C:\MyPictures',6, 1



-- declare @files table (ID int IDENTITY, FileName varchar(100))
-- insert into @files execute xp_cmdshell 'dir C:\MyPictures /b'
-- select * from @files

Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_Ezdenti_ExportImage_to_Bimaran_Image' AND type = 'P')
	 begin
	 set @old_name='sp_Ezdenti_ExportImage_to_Bimaran_Image'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_Ezdenti_ExportImage_to_Bimaran_Image',@old_name;
   end
Go

Go
create PROCEDURE [dbo].[sp_Ezdenti_ExportImage_to_Bimaran_Image] (
-- by alich 1398/09/04
   @transferd_img_id  int
  ,@transferd_filename NVARCHAR (100)  
  ,@code_bimar int
   ,@Fpath NVARCHAR (2000)
   )
AS
BEGIN


   if not EXISTS (select id from Bimaran_Image  where transferd_filename=@transferd_filename and transferd_img_id=@transferd_img_id )
   BEGIN
      DECLARE @tsql NVARCHAR (2000);
      SET NOCOUNT ON

    SET @tsql = 'insert into bimaran_image (code_bimar,transferd_img_id,transferd_filename, tarikh,sharh,insert_time, image_bimar) ' +
               ' SELECT ' + '''' + LTRIM(@code_bimar) + '''' + ',' + '''' +LTRIM(@transferd_img_id)+ ''''+ ',' + '''' +@transferd_filename+ ''''+ ','+ '''' +dbo.GregorianToPersian(convert(varchar, getdate(), 111)) + '''' + ',' + '''' + ' transferd with sp ' + '''' +',' + '''' + convert(varchar, getdate(), 25) + '''' + ', * ' + 
                'FROM Openrowset( Bulk ' + '''' +@Fpath + '''' + ', Single_Blob) as img'
   --select @tsql
   EXEC (@tsql)
   SET NOCOUNT OFF

   END
   
END

-- exec  sp_ImportImage_to_NeedSoft_Bimaran_Image  5280,'C:\MyPictures\Input\Dragon.jpg'
-- insert into bimaran_image (code_bimar, tarikh, image_bimar)  SELECT '1','1398/01/01', * FROM Openrowset( Bulk 'C:\MyPictures\Input\Dragon.jpg', Single_Blob) as img
--select * from Bimaran_Image order by Id DESC
Go
-- 1398/09/06
Go
ALTER TABLE [dbo].[bimaran]
   ADD  [foreigners] [bit] NULL  
GO

ALTER TABLE [dbo].[sorat_hesabe_bimarestan]
   ADD  [takhfif] [money] NULL  
GO

-- 1398/09/16
CREATE TABLE [dbo].[Dynamics_Operation](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[operation_name] [nvarchar](200) NOT NULL,
	[sp_name] [nvarchar](100) NOT NULL,
	[active] [bit] NULL,
 CONSTRAINT [PK_Dynamics_Operation] PRIMARY KEY CLUSTERED 
(
	[id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO





Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_sms_karkerd_koli_for_modir' AND type = 'P')
	 begin
	 set @old_name='sp_sms_karkerd_koli_for_modir'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_sms_karkerd_koli_for_modir',@old_name;
   end
Go
Create PROCEDURE [dbo].[sp_sms_karkerd_koli_for_modir]
AS
BEGIN

  -- exec sp_sms_karkerd_koli_for_modir
 -- delete Auto_SMS where code_babat=9
  -- Formatting a number with thousand separators
 -- FORMAT(1233, 'N0')  
 -- use in sql 2012

  DECLARE @Miladi_Today char(10);
  DECLARE @Miladi_Yesterday char(10);
  DECLARE @Shamsi_Today char(10);
  DECLARE @Shamsi_Yesterday char(10);

  DECLARE @from_time char(16);
  DECLARE @to_time char(16);

  SET @Miladi_Today = CONVERT(varchar(10), GETDATE(), 111);
  SET @Miladi_Yesterday = CONVERT(varchar(10), GETDATE() - 1, 111);
  SET @Shamsi_Today = dbo.GregorianToPersian(@Miladi_Today)
  SET @Shamsi_Yesterday = dbo.GregorianToPersian(@Miladi_Yesterday)

  SET @from_time = @Miladi_Yesterday + ' 08:00'
  SET @to_time = @Miladi_Today + ' 08:00'
 -- SET @to_time = @Miladi_Today + ' 23:00'


  DECLARE @bimeh int = 0
  DECLARE @bes int = 0
  DECLARE @naghd int = 0
  DECLARE @check int = 0
  DECLARE @bargashti int = 0
  DECLARE @pos int = 0
  DECLARE @mokammel int = 0
  DECLARE @yaraneh int = 0

  DECLARE @code_babat int = 9

  DECLARE @mob varchar(100)
  DECLARE @SMS_MSG nvarchar(1000) = ''
  DECLARE @onvan nvarchar(200)=''

  --1
  SELECT
    @bes = SUM(r_bes)
  FROM morajeat
  WHERE insert_time BETWEEN @from_time AND @to_time
  IF @bes IS NULL
    SET @bes = 0
	if @bes <> 0
	set @SMS_MSG=@SMS_MSG+'Kol='+FORMAT(@bes,'N0')+CHAR(13)

  -- Formatting a number with thousand separators
 -- FORMAT(1233, 'N0') 

--2
  SELECT
    @bimeh = SUM(r_bimeh)
  FROM morajeat
  WHERE insert_time BETWEEN @from_time AND @to_time
  IF @bimeh IS NULL
    SET @bimeh = 0
	if @bimeh <> 0
	set @SMS_MSG=@SMS_MSG+'Bimeh='+FORMAT(@bimeh,'N0')+CHAR(13)
  
 --3 
  SELECT
    @naghd = SUM(r_bes)
  FROM morajeat
  WHERE code_pay = 1
  AND insert_time BETWEEN @from_time AND @to_time
  IF @naghd IS NULL
    SET @naghd = 0

	if @naghd <> 0
	set @SMS_MSG=@SMS_MSG+'Naghd='+FORMAT(@naghd,'N0')+CHAR(13)
  
  --4
  SELECT
    @check = SUM(r_bes)
  FROM morajeat
  WHERE code_pay = 2
  AND insert_time BETWEEN @from_time AND @to_time
  IF @check IS NULL
    SET @check = 0
   if @check <> 0
	set @SMS_MSG=@SMS_MSG+'Check='+FORMAT(@check,'N0')+CHAR(13)
  
  --5
  SELECT
    @pos = SUM(r_bes)
  FROM morajeat
  WHERE code_pay = 3
  AND insert_time BETWEEN @from_time AND @to_time
  IF @pos IS NULL
    SET @pos = 0
   if @pos <> 0
	set @SMS_MSG=@SMS_MSG+'Pos='+FORMAT(@pos,'N0')+CHAR(13)
  
 --6 
  SELECT
    @bargashti = SUM(r_bes)
  FROM morajeat
  WHERE code_pay = 4
  AND insert_time BETWEEN @from_time AND @to_time
  IF @bargashti IS NULL
    SET @bargashti = 0
	 if @bargashti <> 0
	set @SMS_MSG=@SMS_MSG+'Barghashti='+FORMAT(@bargashti,'N0')+CHAR(13)
  
--7
  SELECT
    @mokammel = SUM(r_mokammel)
  FROM morajeat
  where insert_time BETWEEN @from_time AND @to_time
  IF @mokammel IS NULL
    SET @mokammel = 0
	 if @mokammel <> 0
	set @SMS_MSG=@SMS_MSG+'Mokammel='+FORMAT(@mokammel,'N0')+CHAR(13)
--8  
  SELECT
    @yaraneh = SUM(r_yaraneh)
  FROM morajeat
  where insert_time BETWEEN @from_time AND @to_time
  IF @yaraneh IS NULL
    SET @yaraneh = 0
	 if @yaraneh <> 0
	set @SMS_MSG=@SMS_MSG+'Yaraneh='+FORMAT(@yaraneh,'N0')+CHAR(13)

--9
   set @SMS_MSG=@SMS_MSG+ @Shamsi_Yesterday+CHAR(13)

--10 
  -- select @onvan=onvan from setting where id=1
   set @onvan='New Center'
   set @SMS_MSG=@SMS_MSG+@onvan+CHAR(13)

  SELECT
    @mob = SMS_Number_Manager
  FROM setting
  
  
  --set @SMS_MSG='Bes:'+cast(@bes as nvarchar)+' '
  --+' Bimeh:'+cast(@bimeh as nvarchar)+''+' Naghd:'
  --+cast(@naghd as nvarchar)+' '+'Pos:'+cast(@pos as nvarchar)+' '
  --+'check:'+cast(@check as nvarchar) +' '+'bargashti:'
  --+cast(@bargashti as nvarchar) + ' from :'+@from_time  +' to :'+@to_time


  ---- for test
  --SELECT
  --  @Miladi_Today,
  --  @Miladi_Yesterday,
  --  @Shamsi_Today,
  --  @from_time,
  --  @to_time
  ---- for test
 --SELECT
 -- @SMS_MSG

	
  IF NOT EXISTS (SELECT TOP 1
      id
    FROM Auto_SMS
    WHERE code_babat = @code_babat
    AND tarikh = @Shamsi_Today)
    INSERT Auto_SMS (SMS_Mobile, SMS_MSG, code_babat, tarikh, saat, sdate, edate, stime, etime)
      VALUES (@mob, @SMS_MSG, @code_babat, @Shamsi_Today, '10:00', @Shamsi_Today, @Shamsi_Today, '12:00', '18:00')

	 

  IF @@ROWCOUNT = 1
    SELECT
      '1' AS s_result,
      '(: Success Insert  ' AS s_message,
      ' From :' + @from_time + '  To:' + @to_time AS s_param
  ELSE
    SELECT
      '0' AS s_result,
      '): Failur Insert  ' AS s_message,
      ' From :' + @from_time + '  To:' + @to_time AS s_param

  -- for test
  --SELECT TOP 1
  --  *
  --FROM Auto_SMS
  --ORDER BY id DESC

END
-- exec sp_sms_karkerd_koli_for_modir
-- delete Auto_SMS where code_babat=9





GO

IF NOT EXISTS (SELECT
    *
  FROM Dynamics_Operation
  WHERE sp_name = 'sp_sms_karkerd_koli_for_modir')
BEGIN
  INSERT INTO Dynamics_Operation (operation_name
  , sp_name
  , active
  )
    VALUES (N' ایجاد پیامک کارکرد کلی برای مدیریت ', 'sp_sms_karkerd_koli_for_modir',  1)
END

GO
IF NOT EXISTS (SELECT
    *
  FROM Dynamics_Operation
  WHERE sp_name = 'transfer_all_bimaran_to_Ezdenti')
BEGIN
  INSERT INTO Dynamics_Operation (operation_name
  , sp_name
  , active
  )
    VALUES (N' انتقال لیست بیماران به ایزی دنت ای ', 'transfer_all_bimaran_to_Ezdenti',  1)
END

Go

IF NOT EXISTS (SELECT
    *
  FROM Dynamics_Operation
  WHERE sp_name = 'sp_Ezdenti_e2_img_ExportImage_all')
BEGIN
  INSERT INTO Dynamics_Operation (operation_name
  , sp_name
  , active
  )
    VALUES (N' انتقال تصاویر ایزی دنت ای به  برنامه ', 'sp_Ezdenti_e2_img_ExportImage_all',  1)
END

Go
IF NOT EXISTS (SELECT
    *
  FROM Dynamics_Operation
  WHERE sp_name = 'transfer_all_bimaran_to_Easydent4_injek')
BEGIN
  INSERT INTO Dynamics_Operation (operation_name
  , sp_name
  , active
  )
    VALUES (N' انتقال بیماران به ایزی دنت 4 ', 'transfer_all_bimaran_to_Easydent4_injek',  1)
END

Go

IF NOT EXISTS (SELECT
    *
  FROM Dynamics_Operation
  WHERE sp_name = 'transfer_all_moshtari_to_bimaran')
BEGIN
  INSERT INTO Dynamics_Operation (operation_name
  , sp_name
  , active
  )
    VALUES (N' انتقال جدول مشتریان به بیماران با کد منفی ', 'transfer_all_moshtari_to_bimaran',  1)
END

Go

Go
ALTER TABLE [dbo].[users]
   add [ab_run_Dynamics_Operation] [bit] NULL 
Go

GO
update bimaran set code_moshtari=0 where code_moshtari is null
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'transfer_all_moshtari_to_bimaran' AND type = 'P')
	 begin
	 set @old_name='transfer_all_moshtari_to_bimaran'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'transfer_all_moshtari_to_bimaran',@old_name;
   end
Go
Go
create PROCEDURE [dbo].[transfer_all_moshtari_to_bimaran]
AS
BEGIN
-- exec transfer_all_moshtari_to_bimaran
  DECLARE @number_transferred int=0
  DECLARE @min_code_bimar int
  DECLARE @code_moshtari int
  DECLARE @name_moshtari nvarchar(50)
  DECLARE @mobil_moshtari nvarchar(50)
  DECLARE @tel_moshtari nvarchar(50)
  DECLARE @fax_moshtari nvarchar(50)
  DECLARE @email_moshtari nvarchar(50)

  IF EXISTS (SELECT TOP 1
      code_moshtari
    FROM moshtari
    WHERE code_moshtari NOT IN (SELECT
      code_moshtari
    FROM bimaran
    WHERE code_moshtari IS NOT NULL))
  BEGIN
    DECLARE cursor_moshtari CURSOR FAST_FORWARD FOR
    SELECT
      code_moshtari,
      RTRIM(LTRIM(name_moshtari)),
      Mobil,
      tel,
      fax,
      email
    FROM moshtari
    WHERE code_moshtari NOT IN (SELECT
      code_moshtari
    FROM bimaran
    WHERE code_moshtari IS NOT NULL)
    ORDER BY code_moshtari

    OPEN cursor_moshtari
    FETCH NEXT FROM cursor_moshtari INTO @code_moshtari, @name_moshtari, @mobil_moshtari, @tel_moshtari, @fax_moshtari, @email_moshtari

    WHILE @@FETCH_STATUS = 0
    BEGIN

      SELECT
        @min_code_bimar = MIN(code_bimar)
      FROM bimaran
      IF @min_code_bimar >= 0
        SET @min_code_bimar = -1
      ELSE
        SET @min_code_bimar = @min_code_bimar - 1

      INSERT bimaran (code_bimar,
      name,
      famil,
      Mobil,
      Tel,
      Tel2,
      email,
      code_moshtari)
        VALUES (@min_code_bimar, @name_moshtari, @name_moshtari, @mobil_moshtari, @tel_moshtari, @fax_moshtari, @email_moshtari, @code_moshtari)

      IF @@ROWCOUNT = 1
        SET @number_transferred = @number_transferred + 1

      FETCH NEXT FROM cursor_moshtari INTO @code_moshtari, @name_moshtari, @mobil_moshtari, @tel_moshtari, @fax_moshtari, @email_moshtari
    END
    CLOSE cursor_moshtari
    DEALLOCATE cursor_moshtari

  END
  SELECT
    @number_transferred AS s_result,
    'Number Of transferred=' + LTRIM(@number_transferred) + '   sp :  ' + OBJECT_NAME(@@PROCID) AS s_message,
    ' no param ' AS s_param
END
-- exec transfer_all_moshtari_to_bimaran
GO

--1398/09/17
Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_send_sms_all' AND type = 'P')
	 begin
	 set @old_name='sp_send_sms_all'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_send_sms_all',@old_name;
   end
Go

Go
create PROCEDURE [dbo].[sp_send_sms_all]
  -- Add the parameters for the stored procedure here
  -- Exec sp_send_sms '1397/10/25', '10:00', 99 , 4, 1,441698
(
  @tarikh nvarchar(10),
  @saat nvarchar(5) ,
  @code_operator int,
  @send_taki bit,
  @id_sms int
  )
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @username nvarchar(100) = 'testasanakns'
	DECLARE @password nvarchar(100) = 'NeedSoft'
	DECLARE @source nvarchar(100) = '982100066389654'
	DECLARE @sms_msg nvarchar(1024)
	DECLARE @sms_mobile nvarchar(50)
	DECLARE @id_auto int

	IF(@send_taki = 0)
	BEGIN

		DECLARE cursor_select_auto_sms CURSOR FAST_FORWARD
		FOR SELECT TOP 10  id,SMS_MSG, SMS_Mobile FROM Auto_SMS 
			WHERE @tarikh BETWEEN sdate AND edate 
				AND @saat BETWEEN stime AND etime 
			    AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))
			ORDER BY id DESC

		OPEN cursor_select_auto_sms
		FETCH NEXT FROM cursor_select_auto_sms INTO @id_auto, @sms_msg, @sms_mobile

		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC api_asanak_send_sms_proc @username, @password, @source, @sms_msg ,@sms_mobile, @id_auto 
		
			FETCH NEXT FROM cursor_select_auto_sms INTO @id_auto, @sms_msg, @sms_mobile
		END

		CLOSE cursor_select_auto_sms
		DEALLOCATE cursor_select_auto_sms
	END
	ELSE
	BEGIN

		SELECT  @id_auto = id, @sms_msg = SMS_MSG,@sms_mobile = SMS_Mobile FROM Auto_SMS 
			WHERE id = @id_sms
				AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))
		IF (@@ROWCOUNT > 0)
		BEGIN
			EXEC api_asanak_send_sms_proc @username, @password, @source, @sms_msg, @sms_mobile, @id_auto 
		END
		ELSE
		BEGIN
			PRINT('Not Find This ID In SMS Taki SELECT')
		END
	END

/***********************************

Description: Send Sms Taki And Gorohi With Restful Api   
Author: Golozari Ali - Nobody :) 
Company: NeedSoft 
Create Date: 2019/01/13 - 1397/10/23
Create Time: 18:00
Param: @tarikh, @saat, @code_babat, @code_operator, @send_taki, @id_sms
Return: No Return Param  
Modified Date: 2019/01/15 - 1397/10/25
Modified Time: 15:40
Modification: 1- Add Fiture Send Taki 
			  2- Add Drop Procedure If Exists

***********************************/ 

/***********************************

1- For Test => Gorohi
		SELECT TOP 10  SMS_MSG, SMS_Mobile FROM Auto_SMS 
		WHERE '1397/10/25' BETWEEN sdate AND edate 
			AND '10:00' BETWEEN stime AND etime 
			AND code_babat = 99
			AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
			AND ((SendAnswer < 1) or (SendAnswer is null))
		ORDER BY id DESC


2- For Test => Taki
		SELECT   id, SMS_MSG, SMS_Mobile FROM Auto_SMS 
			WHERE id = 441698
				AND len(SMS_Mobile) >= 11 and SMS_Mobile like '09%'
				AND ((SendAnswer < 1) or (SendAnswer is null))

***********************************/

END

Go

ALTER TABLE [dbo].[settingd]
    add [Enable_Auto_Ghabz_with_FR] bit Null
Go
--update settingd set Enable_Auto_Ghabz_with_FR=1
Go

create  procedure sp_search_text_in_db( @search_text varchar(30))
as
begin

SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc
  FROM sys.sql_modules m
       INNER JOIN
       sys.objects o
         ON m.object_id = o.object_id
 WHERE m.definition Like '%'+@search_text+'%';

 end
 -- sp_search_text_in_db nu
 Go



 
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_report_last_tarikh_bimaran_with_no_vaght' AND type = 'P')
	 begin
	 set @old_name='sp_report_last_tarikh_bimaran_with_no_vaght'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_report_last_tarikh_bimaran_with_no_vaght',@old_name;
   end
Go
CREATE PROCEDURE [dbo].[sp_report_last_tarikh_bimaran_with_no_vaght](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));
set @code_ranandeh=LTRIM(RTRIM(@code_ranandeh));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN
    
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   begin

   --  ایجاد جدول موقت 
    select code_bimar,name,famil,Mobil,(select count(*) from vaght_dehi 
    where code_bimar=b.code_bimar and tarikh > @from_tarikh ) as tedad_vaght  
    into #temp  from bimaran b  where last_tarikh between @from_tarikh and @to_tarikh
	  
    -- انتحاب از جدول موقت 
	  
	select * from #temp where tedad_vaght < 1  order by tedad_vaght DESC 

   end
   else
   select 0 as s_result ,' no tarikh condition ' as s_message , 'no param ' as s_param

END

GO

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'sp_report_last_tarikh_bimaran_with_vaght' AND type = 'P')
	 begin
	 set @old_name='sp_report_last_tarikh_bimaran_with_vaght'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'sp_report_last_tarikh_bimaran_with_vaght',@old_name;
   end
Go

CREATE PROCEDURE [dbo].[sp_report_last_tarikh_bimaran_with_vaght](
-- پارامتر های ورودی 
@from_tarikh char(10),
@to_tarikh char(10),
@code_bimar varchar(10), 
@code_bimeh varchar(10),
@code_bakhsh  varchar(10),
@code_pezeshk varchar(10),
@code_darman varchar(10),
@code_shift	varchar(10),
@code_user_insert varchar(10),
@code_pay varchar(10),
@code_shobeh varchar(10), 
@from_time varchar(20),
@to_time varchar(20),
@sh_kargozini varchar(10),	
@code_ertebat	varchar(10),
@code_shift_str	varchar(5000),
@code_bimeh_str	varchar(5000),
@code_bakhsh_str varchar(5000),
@code_pezeshk_str varchar(5000),
@code_yaraneh varchar(10),	
@code_mokammel	varchar(10),
@code_dastyar varchar(10),
@code_ranandeh varchar(10)	

)
AS
-- از بین بردن فضای خالی
set @from_tarikh=LTRIM(RTRIM(@from_tarikh));
set @to_tarikh=LTRIM(RTRIM(@to_tarikh));
set @code_bimar=LTRIM(RTRIM(@code_bimar));
set @code_bimeh=LTRIM(RTRIM(@code_bimeh));
set @code_bakhsh=LTRIM(RTRIM(@code_bakhsh));
set @code_pezeshk=LTRIM(RTRIM(@code_pezeshk));
set @code_darman=LTRIM(RTRIM(@code_darman));
set @code_shift=LTRIM(RTRIM(@code_shift));
set @code_user_insert=LTRIM(RTRIM(@code_user_insert));
set @code_pay=LTRIM(RTRIM(@code_pay));
set @code_shobeh=LTRIM(RTRIM(@code_shobeh));
set @from_time=LTRIM(RTRIM(@from_time));
set @to_time=LTRIM(RTRIM(@to_time));
set @sh_kargozini =LTRIM(RTRIM(@sh_kargozini ));
set @code_ertebat=LTRIM(RTRIM(@code_ertebat));
set @code_shift_str=LTRIM(RTRIM(@code_shift_str));
set @code_bimeh_str=LTRIM(RTRIM(@code_bimeh_str));
set @code_bakhsh_str=LTRIM(RTRIM(@code_bakhsh_str));
set @code_pezeshk_str=LTRIM(RTRIM(@code_pezeshk_str));
set @code_yaraneh=LTRIM(RTRIM(@code_yaraneh));
set @code_mokammel=LTRIM(RTRIM(@code_mokammel));
set @code_dastyar=LTRIM(RTRIM(@code_dastyar));
set @code_ranandeh=LTRIM(RTRIM(@code_ranandeh));

--  تعریف متغیر ها
DECLARE @mywhere nvarchar(3000);
DECLARE @mystmt nvarchar(3000);
DECLARE @mygroup nvarchar(500);
DECLARE @myorder nvarchar(500);


--  از حالت نال در اوردن 
set @mywhere =''
set @mystmt=''
set @mygroup=''
set @myorder=''


BEGIN
    
   if(LEN(@from_tarikh)>0) and (LEN(@to_tarikh)>0) 
   begin

   --  ایجاد جدول موقت 
    select code_bimar,name,famil,Mobil,(select count(*) from vaght_dehi 
    where code_bimar=b.code_bimar and tarikh > @from_tarikh ) as tedad_vaght  
    into #temp  from bimaran b  where last_tarikh between @from_tarikh and @to_tarikh
	  
    -- انتحاب از جدول موقت 
	  
	select * from #temp where tedad_vaght >= 1  order by tedad_vaght DESC 

   end
   else
   select 0 as s_result ,' no tarikh condition ' as s_message , 'no param ' as s_param

END

GO
---------------------------------------------------------
IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_report_last_tarikh_bimaran_with_vaght')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N' گزارش بیماران چند ماه گذشته نیامده و وقت  گرفته اند  ', 'sp_report_last_tarikh_bimaran_with_vaght', 'sp_report_last_tarikh_bimaran_with_vaght.fr3', 1, 'sp_parameters', 1,1)

END

GO

IF NOT EXISTS (SELECT
    *
  FROM SP_Daynamic_Report
  WHERE sp_name = 'sp_report_last_tarikh_bimaran_with_no_vaght')
BEGIN
  INSERT INTO SP_Daynamic_Report (report_name
  , sp_name
  , fr_name
  , active
  , sp_parameters
  , rw
  ,code_system)
    VALUES (N'   گزارش بیمارانی که چند ماه نیامده و وقت نگرفته اند   ', 'sp_report_last_tarikh_bimaran_with_no_vaght', 'sp_report_last_tarikh_bimaran_with_no_vaght.fr3', 1, 'sp_parameters', 1,1)

END

GO

--  1398/10/12
--  کنترل ثبت اطلاعات در مراجعات و وقت دهی قبل از ثبت و بعد از ان 

ALTER TABLE [dbo].[settingc]
    add [check_sp_vaght_dehi_befor_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_vaght_dehi_after_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_vaght_dehi_alarm_befor_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_morajeat_alram_befor_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_morajeat_after_Save_] bit Null
Go
ALTER TABLE [dbo].[settingc]
    add [check_sp_morajeat_befor_Save_] bit Null
Go

--  update settingc set check_sp_vaght_dehi_befor_Save_=1
Go
--  update settingc set check_sp_vaght_dehi_after_Save_=1
Go
--  update settingc set check_sp_morajeat_befor_Save_=1
Go
--  update settingc set check_sp_morajeat_befor_Save_=1
Go
--  update settingc set check_sp_vaght_dehi_alarm_befor_Save_=1
Go
--  update settingc set check_sp_morajeat_alram_befor_Save_=1
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = '_sp_vaght_dehi_alarm_befor_Save_' AND type = 'P')
	 begin
	 set @old_name='_sp_vaght_dehi_alarm_befor_Save_'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename '_sp_vaght_dehi_alarm_befor_Save_',@old_name;
   end
Go

create PROCEDURE [dbo].[_sp_vaght_dehi_alarm_befor_Save_] (
-- 1398/10/12 by AliCh NeedSoft
@code_bimar varchar(10),
@code_pezeshk varchar(10),
@tarikh_vaght char(10),
@saat_vaght char(5),
@meghdar_vaght varchar(10),
@code_unit varchar(10),
@code_bimeh varchar(10),
@code_bakhsh varchar(10),
@code_darman varchar(10))
AS

  SET @code_bimar = LTRIM(RTRIM(@code_bimar));
  SET @code_bimeh = LTRIM(RTRIM(@code_bimeh));
  SET @code_pezeshk = LTRIM(RTRIM(@code_pezeshk));
  SET @tarikh_vaght = LTRIM(RTRIM(@tarikh_vaght));
  SET @saat_vaght = LTRIM(RTRIM(@saat_vaght));
  SET @meghdar_vaght = LTRIM(RTRIM(@meghdar_vaght));
  SET @code_unit = LTRIM(RTRIM(@code_unit));
  SET @code_bakhsh = LTRIM(RTRIM(@code_bakhsh));
  SET @code_darman = LTRIM(RTRIM(@code_darman));
  BEGIN

    IF (LEN(@code_bimar) > 0)
      AND (LEN(@code_pezeshk) > 0)
      AND (LEN(@tarikh_vaght) = 10)
    BEGIN

      DECLARE @tedad_vaght int = 0

      SELECT
        @tedad_vaght = COUNT(*)
      FROM vaght_dehi
      WHERE ((code_bimar = @code_bimar)
      AND (code_pezeshk = @code_pezeshk)
      AND (tarikh >= @tarikh_vaght))


     SELECT
        @tedad_vaght AS s_result,
        ' تعدا د وقتهای داده شده به این بیمار '+CHAR(13)+'با این پزشک و تاریخ بزرگتر و مساوی این تاریخ  ' +CHAR(13)+ LTRIM(@tedad_vaght) +CHAR(13)+ '  مورد است  '   AS s_message,
        ' @code_bimar=' + LTRIM(@code_bimar) + ' @code_pezeshk=' + LTRIM(@code_pezeshk) + ' @tarikh_vaght=' + LTRIM(@tarikh_vaght) AS s_param



      --SELECT
      --  @tedad_vaght AS s_result,
      --  ':) Tedad_vaght=' + LTRIM(@tedad_vaght) + '   ' + OBJECT_NAME(@@PROCID) AS s_message,
      --  ' @code_bimar=' + LTRIM(@code_bimar) + ' @code_pezeshk=' + LTRIM(@code_pezeshk) + ' @tarikh_vaght=' + LTRIM(@tarikh_vaght) AS s_param


    END
    ELSE
      SELECT
        -100 AS s_result,
        ':( no condition to run sp ' + OBJECT_NAME(@@PROCID) AS s_message,
        ' @code_bimar=' + LTRIM(@code_bimar) + ' @code_pezeshk=' + LTRIM(@code_pezeshk) + ' @tarikh_vaght=' + LTRIM(@tarikh_vaght) AS s_param

  END;
-- 1398/10/12 by AliCh NeedSoft
-- EXEC
/*
exec _sp_vaght_dehi_alarm_befor_Save_ 
 @code_bimar='29128'  ,
 @code_pezeshk='63749'  ,
 @tarikh_vaght='1398/07/15'  ,
 @saat_vaght='10:10' ,
 @meghdar_vaght=''  ,
 @code_unit='1'  ,
 @code_bimeh='2'  ,
 @code_bakhsh=''  ,
 @code_darman='1669'

*/

GO
ALTER TABLE [dbo].[vaght_dehi]
    add [to_saat] char(5) Null
Go


declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = '_2341_create_timeing' AND type = 'P')
	 begin
	  set @old_name='_2341_create_timeing'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename '_2341_create_timeing',@old_name;
   end
Go

Go
create PROCEDURE [dbo].[_2341_create_timeing] (@fday char(10),
@tday char(10),
@StartTime time(2),
@EndTime time(2),
@amount smallint,
@c_week char(1),
@cp_expert varchar(10),
@cs varchar(10),
@time_count int
)
AS
BEGIN
  DECLARE @tc int=0

  DECLARE @Record_Count_In_daysy int
  DECLARE @daysy char(10)
  DECLARE @week int
  DECLARE @stime time(2)
  DECLARE @etime time(2)
  DECLARE @Record_Count_Create int=0
  DECLARE @s_message nvarchar(300)=''
  
  SET @Record_Count_In_daysy = 0;

  IF ((LEN(@fday) = 10)
    AND (LEN(@tday) = 10)
    AND (STR(@c_week) BETWEEN 0 AND 6)
    AND (@amount BETWEEN 0 AND 1440))
  BEGIN
    SET NOCOUNT ON;
    SELECT
      @Record_Count_In_daysy = COUNT(*)
    FROM tarikh
    WHERE tarikh BETWEEN @fday AND @tday
    AND code_week = @c_week

    IF (@Record_Count_In_daysy BETWEEN 1 AND 52)
    BEGIN
      DECLARE cursor_daysy CURSOR FAST_FORWARD FOR
      SELECT
        tarikh,
        code_week
      FROM tarikh
      WHERE tarikh BETWEEN @fday AND @tday
      AND code_week = @c_week
      ORDER BY tarikh

      OPEN cursor_daysy
      FETCH NEXT FROM cursor_daysy INTO @daysy, @week

      WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @stime = @StartTime
        SET @etime = (RIGHT('0' + CAST(DATEPART(HOUR, DATEADD(mi, @amount, @stime)) AS varchar(2)), 2) + ':' +
        RIGHT('0' + CAST(DATEPART(MINUTE, DATEADD(mi, @amount, @stime)) AS varchar(2)), 2))
        WHILE (@etime <= @EndTime)
        BEGIN
		      set @tc=@time_count
              while (@tc > 0 )
			  begin
					  INSERT INTO vaght_dehi( code_darman,tarikh,code_week, saat, to_saat, meghdar, code_pezeshk,code_unit)
						VALUES ( @cs, @daysy,@c_week, @stime, @etime, @amount, @cp_expert,0)
					  SET @Record_Count_Create = @Record_Count_Create + 1;  
					  set @tc=@tc-1  
              end


          SET @stime = @etime
          SET @etime = (RIGHT('0' + CAST(DATEPART(HOUR, DATEADD(mi, @amount, @etime)) AS varchar(2)), 2) + ':' +
          RIGHT('0' + CAST(DATEPART(MINUTE, DATEADD(mi, @amount, @etime)) AS varchar(2)), 2))
        END
        FETCH NEXT FROM cursor_daysy INTO @daysy, @week
      END
      CLOSE cursor_daysy
      DEALLOCATE cursor_daysy
      SET @s_message = ':)  Success  ' + CHAR(13) + CHAR(13) + RTRIM(LTRIM(STR(@Record_Count_Create))) + '  row created for '+RTRIM(LTRIM(str(@Record_Count_In_daysy)))+' day week' + CHAR(13) + CHAR(13) + OBJECT_NAME(@@PROCID);
	  select @Record_Count_Create as s_result , @s_message as s_message ,'no param ' as s_param
    END
    ELSE
      begin
      SET @s_message = ':(  Failure  ' + CHAR(13) + CHAR(13) + ' No Record in daysy with conditions  Record_Count_In_daysy BETWEEN 1 AND 52 for week ' + CHAR(13) + CHAR(13) + OBJECT_NAME(@@PROCID);
	  select '0' as s_result , @s_message as s_message ,'no param ' as s_param
	  end
  END
  ELSE
    begin
    SET @s_message = ':(  Failure' + CHAR(13) + CHAR(13) + ' No Conditions to execute  fday,tday,c_week,amount  ' + CHAR(13) + CHAR(13) + OBJECT_NAME(@@PROCID);
	select '0' as s_result , @s_message as s_message ,'no param ' as s_param
	end
END

/*

EXEC _2341_create_timeing '1398/10/22','1398/10/22','08:00','09:00','60','1','1','1','1'

@tday char(10),
@StartTime time(2),
@EndTime time(2),
@amount smallint,
@c_week char(1),
@cp_expert varchar(10),
@cs varchar(10),
@time_count int
--delete vaght_dehi

INSERT INTO timeing (cp, cs, sdate,c_week, stime, etime, amount, cp_expert,c_unit)
            VALUES (0, @cs, @daysy,@c_week, @stime, @etime, @amount, @cp_expert,0)

*/
Go


create PROCEDURE [dbo].[_2340_create_timeing] (@fday char(10),
@tday char(10),
@StartTime time(2),
@EndTime time(2),
@amount smallint,
@c_week char(1),
@cp_expert varchar(10),
@cs varchar(10)
)
AS
BEGIN
  DECLARE @Record_Count_In_daysy int
  DECLARE @daysy char(10)
  DECLARE @week int
  DECLARE @stime time(2)
  DECLARE @etime time(2)
  DECLARE @Record_Count_Create int=0
  DECLARE @s_message nvarchar(300)=''
  
  SET @Record_Count_In_daysy = 0;

  IF ((LEN(@fday) = 10)
    AND (LEN(@tday) = 10)
    AND (STR(@c_week) BETWEEN 0 AND 6)
    AND (@amount BETWEEN 0 AND 1440))
  BEGIN
    SET NOCOUNT ON;
    SELECT
      @Record_Count_In_daysy = COUNT(*)
    FROM tarikh
    WHERE tarikh BETWEEN @fday AND @tday
    AND code_week = @c_week

    IF (@Record_Count_In_daysy BETWEEN 1 AND 52)
    BEGIN
      DECLARE cursor_daysy CURSOR FAST_FORWARD FOR
      SELECT
        tarikh,
        code_week
      FROM tarikh
      WHERE tarikh BETWEEN @fday AND @tday
      AND code_week = @c_week
      ORDER BY tarikh

      OPEN cursor_daysy
      FETCH NEXT FROM cursor_daysy INTO @daysy, @week

      WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @stime = @StartTime
        SET @etime = (RIGHT('0' + CAST(DATEPART(HOUR, DATEADD(mi, @amount, @stime)) AS varchar(2)), 2) + ':' +
        RIGHT('0' + CAST(DATEPART(MINUTE, DATEADD(mi, @amount, @stime)) AS varchar(2)), 2))
        WHILE (@etime <= @EndTime)
        BEGIN
          INSERT INTO vaght_dehi( code_darman,tarikh,code_week, saat, to_saat, meghdar, code_pezeshk,code_unit)
            VALUES ( @cs, @daysy,@c_week, @stime, @etime, @amount, @cp_expert,0)
          SET @Record_Count_Create = @Record_Count_Create + 1;
          SET @stime = @etime
          SET @etime = (RIGHT('0' + CAST(DATEPART(HOUR, DATEADD(mi, @amount, @etime)) AS varchar(2)), 2) + ':' +
          RIGHT('0' + CAST(DATEPART(MINUTE, DATEADD(mi, @amount, @etime)) AS varchar(2)), 2))
        END
        FETCH NEXT FROM cursor_daysy INTO @daysy, @week
      END
      CLOSE cursor_daysy
      DEALLOCATE cursor_daysy
      SET @s_message = ':)  Success  ' + CHAR(13) + CHAR(13) + RTRIM(LTRIM(STR(@Record_Count_Create))) + '  row created for '+RTRIM(LTRIM(str(@Record_Count_In_daysy)))+' day week' + CHAR(13) + CHAR(13) + OBJECT_NAME(@@PROCID);
	  select @Record_Count_Create as s_result , @s_message as s_message
    END
    ELSE
      begin
      SET @s_message = ':(  Failure  ' + CHAR(13) + CHAR(13) + ' No Record in daysy with conditions  Record_Count_In_daysy BETWEEN 1 AND 52 for week ' + CHAR(13) + CHAR(13) + OBJECT_NAME(@@PROCID);
	  select '0' as s_result , @s_message as s_message
	  end
  END
  ELSE
    begin
    SET @s_message = ':(  Failure' + CHAR(13) + CHAR(13) + ' No Conditions to execute  fday,tday,c_week,amount  ' + CHAR(13) + CHAR(13) + OBJECT_NAME(@@PROCID);
	select '0' as s_result , @s_message as s_message
	end
END

/*

EXEC _2340_create_timeing '1398/10/22','1398/12/22','08:00','15:00','75','0','1','1'


          INSERT INTO timeing (cp, cs, sdate,c_week, stime, etime, amount, cp_expert,c_unit)
            VALUES (0, @cs, @daysy,@c_week, @stime, @etime, @amount, @cp_expert,0)



*/
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'Drop_30_Procedure_And_Table_Created_Between' AND type = 'P')
	 begin
	 set @old_name='Drop_30_Procedure_And_Table_Created_Between'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'Drop_30_Procedure_And_Table_Created_Between',@old_name;
   end

Go
Create procedure Drop_30_Procedure_And_Table_Created_Between(@ftime datetime,@ttime datetime)
as
begin

declare @object_name_like varchar(200)='%_old_2019%' 
declare @name_sysobjects sysname
declare @type_sysobjects char(2)
declare @deleted_object int=0
declare @sqlst varchar(1000)='' 
DECLARE	@return_value int

if exists (SELECT top 1 name FROM sysobjects
      WHERE  (type = 'P' or type = 'u') and (crdate between @ftime and @ttime)  )
begin
        DECLARE cursor_sysobjects CURSOR FAST_FORWARD FOR
        SELECT top 30 
          name,
		  type
        FROM sysobjects
        WHERE   (type = 'P' or type = 'u') and (crdate between @ftime and @ttime)  

        OPEN cursor_sysobjects
        FETCH NEXT FROM cursor_sysobjects INTO @name_sysobjects,@type_sysobjects

        WHILE @@FETCH_STATUS = 0
        BEGIN


		if  exists (SELECT name FROM sysobjects where name=@name_sysobjects and [type]='P')
        begin
	    	
		   set @sqlst=' DROP PROCEDURE '+ @name_sysobjects
	       exec (@sqlst)
		   set @deleted_object=@deleted_object+1
		   --exec @return_value=@sqlst
		   --set @deleted_object=@deleted_object+@return_value
        end	
		
     
		if  exists (SELECT name FROM sysobjects where name=@name_sysobjects and [type]='U')
        begin
		   set @sqlst=' DROP Table '+ @name_sysobjects
  		   exec (@sqlst)
		   set @deleted_object=@deleted_object+1
		--   exec @return_value=@sqlst
		--   set @deleted_object=@deleted_object+@return_value
        end	
		
  
         FETCH NEXT FROM cursor_sysobjects INTO @name_sysobjects,@type_sysobjects
        END
		
        CLOSE cursor_sysobjects
        DEALLOCATE cursor_sysobjects

        select @deleted_object as s_result,' Number of sysobjects deleted='+ltrim(@deleted_object) as s_message
		
end
else
     select '0' as s_result,'no record found in table sysobjects with condition  '+ @object_name_like as s_message

end
Go


CREATE TABLE [dbo].[users_role_permission](
	[c_role] [int] NOT NULL,
	[c_permission] [int] NOT NULL,
 CONSTRAINT [PK_users_role_itm] PRIMARY KEY CLUSTERED 
(
	[c_role] ASC,
	[c_permission] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[users_role_itm]    Script Date: 01/25/2020 16:42:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[users_role_itm](
	[c_role] [int] NOT NULL,
	[n_role] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_users_role] PRIMARY KEY CLUSTERED 
(
	[c_role] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[users_role]    Script Date: 01/25/2020 16:42:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[users_role](
	[cp] [int] NOT NULL,
	[c_role] [int] NOT NULL,
 CONSTRAINT [PK_users_role_1] PRIMARY KEY CLUSTERED 
(
	[cp] ASC,
	[c_role] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[users_permission_itm]    Script Date: 01/25/2020 16:42:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[users_permission_itm](
	[c_permission] [int] NOT NULL,
	[n_permission] [varchar](100) NOT NULL,
	[descr] [nvarchar](200) NOT NULL,
	[act] [bit] NOT NULL,
	[c_kind] [int] NULL,
 CONSTRAINT [PK_permissions] PRIMARY KEY CLUSTERED 
(
	[c_permission] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC dbo.sp_addextendedproperty @name=N'MS_Description', @value=N'description' , @level0type=N'USER',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'users_permission_itm', @level2type=N'COLUMN',@level2name=N'descr'
GO
EXEC dbo.sp_addextendedproperty @name=N'MS_Description', @value=N'active' , @level0type=N'USER',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'users_permission_itm', @level2type=N'COLUMN',@level2name=N'act'
GO
/****** Object:  Table [dbo].[users_permission]    Script Date: 01/25/2020 16:42:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[users_permission](
	[cp] [int] NOT NULL,
	[c_permission] [int] NOT NULL,
 CONSTRAINT [PK_users_permission] PRIMARY KEY CLUSTERED 
(
	[cp] ASC,
	[c_permission] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
Go
declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = 'Fn_Check_Permission' AND type = 'FN')
	 begin
	 set @old_name='Fn_Check_Permission'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename 'Fn_Check_Permission',@old_name;
   end
Go
create  FUNCTION [dbo].[Fn_Check_Permission]
(
    @cp_user_login int,
	@n_permission varchar(100)
)
RETURNS bit
AS
BEGIN
    DECLARE @ResultVar bit=0;
	DECLARE @c_permission int=0;

	select @c_permission=c_permission from users_permission_itm where n_permission=@n_permission


	IF ((@cp_user_login>=0) and (@c_permission>0))
    IF  EXISTS(select * from users_permission where cp=@cp_user_login and c_permission=@c_permission)
	set  @ResultVar=1
	else
	set @ResultVar=0

	RETURN @ResultVar
end
Go

declare @old_name varchar(200)
IF EXISTS (SELECT name FROM sysobjects
     WHERE name = '_exec_proc' AND type = 'P')
	 begin
	 set @old_name='_exec_proc'+'_old_'+[dbo].[Fn_Now_DateTime]()
	  EXEC sp_rename '_exec_proc',@old_name;
   end
Go
Go
create PROCEDURE [dbo].[_exec_proc] @ProcName varchar(100),
@Params varchar(max),
-- login user cp
@lucp int
 with encryption
AS
BEGIN

 -- DECLARE @IsLogin int = 0
  DECLARE @c_permission int 


   -- if sp name is number
   if (ISNUMERIC(@ProcName)=1)
   begin
       set @c_permission=@ProcName
       select @ProcName=n_permission from users_permission_itm where c_permission=@ProcName and act<> 0
   end


     IF EXISTS (SELECT TOP 1
        1
      FROM sys.procedures p
      WHERE p.name = @ProcName)
    BEGIN TRY
	  -- select @Login_User_cp,@ProcName
      IF ((dbo.Fn_Check_Permission(@lucp,@ProcName) = 1) or (@c_permission <= 2222))
      EXEC (@ProcName + ' ' + @Params)
	  else
	  SELECT  '-1112' as s_result , ':(  No Permission. ' +CHAR(13)+CHAR(13)+@ProcName+ ISNULL(ERROR_MESSAGE(), '') as  s_message,'no param' as s_param
    END TRY
    BEGIN CATCH
      SELECT  '-1117' as s_result , ':(  Invalid Requset. ' +CHAR(13)+CHAR(13)+@ProcName+ ISNULL(ERROR_MESSAGE(), '') as  s_message,'no param' as s_param
    END CATCH

    ELSE
      SELECT '-1118' as s_result, ':(  Stoted procedure '+CHAR(13)+CHAR(13)+@ProcName+' not found' as  s_message,'no param' as s_param

END

--	EXEC ExecProc sp_per_delete,'1,1,1'
--  EXEC _Exec_Proc sp_daysy_select,'','E4371052-FF37-4A2C-B9D8-EBCCE88CA0A9','1'
--  EXEC _Exec_Proc sp_1daysy_select,'','A0E7C6A5-AF57-4300-A0C4-1325981D23A0','1'

Go

ALTER TABLE [dbo].[users]
   add [ab_veiw_R_O_with_user_permission] [bit] NULL 
Go

GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (1, 2225)
GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (1, 2226)
GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (1, 2227)
GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (1, 2228)
GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (1, 2229)
GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (2, 2228)
GO
INSERT [dbo].[users_permission] ([cp], [c_permission]) VALUES (3, 2228)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2223, N'2223 - رزرو', N'2223 - رزرو گزارشات و عملیات', 0, 0)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2224, N'2224  - رزرو', N'2224 - رزرو', 0, 0)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2225, N'_2225_users_permission_select_report_operation', N'مشاهد لیست حقوق  گزارشی  و عملیاتی', 1, 0)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2226, N'_2226_R_Morajeat_User_Insert', N'گزارش لیستی  پذیرش  کاربر ثبت کننده', 1, 11)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2227, N'_2227_R_Vaght_Dehi_User_Insert', N'گزارش لیستی  وقت دهی  کاربر ثبت کننده', 1, 11)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2228, N'_2228_R_Morajeat_SUM_shift', N'گزارش سرجمع شیفت کاری  پذیرش', 0, 11)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2229, N'_2229_R_Morajeat_SUM_pezeshk', N'گزارش سرجمع به تفکیک پزشک پذیرش', 1, 11)
GO
INSERT [dbo].[users_permission_itm] ([c_permission], [n_permission], [descr], [act], [c_kind]) VALUES (2230, N'22302230', N'2230', 1, 11)
GO



CREATE PROCEDURE [dbo].[_2225_users_permission_select_report_operation] (@cp int )
AS
BEGIN
set @cp=LTRIM(RTRIM(@cp))  

if (len(@cp)>0) 
begin
     select c_permission,
	 (select n_permission from users_permission_itm where c_permission=up.c_permission and act<> 0  and c_kind =11) as n_permission, 
	 (select descr from users_permission_itm where c_permission=up.c_permission and act<> 0 and c_kind =11) as report_operation 
	  
	  into #temp
	 from users_permission up where cp=@cp

	 select * from #temp where n_permission is not null

end
else
select 0 as s_result, ':( no condition to run sp : '+OBJECT_NAME(@@PROCID) as s_message ,' cp='+STR(@cp)+' cp='+STR(@cp) as s_param
END

--exec _2225_users_permission_select_report_operation 1

GO


CREATE procedure [dbo].[_2226_R_Morajeat_User_Insert]
(
@fday char(10),
@tday char(10),
@ftime char(20),
@ttime char(20),
@code_user int,
@code_shift	int,
@code_shobeh int,
@code_pay int,
@code_bimeh int,
@code_bakhsh int,
@code_pezeshk int,
@code_dastyar int,
@code_darman int,
@code_bimar int,
@code_ranandeh int,
@code_yaraneh int,
@code_mokammel	int,
@sh_kargozini varchar(20),
@code_ertebat	varchar(20),
@code_shift_str	varchar(500),
@code_bimeh_str	varchar(500),
@code_bakhsh_str varchar(500),
@code_pezeshk_str varchar(500),
@lucp int
)
as
begin

set @fday=RTRIM(LTRIM(@fday))
set @tday=RTRIM(LTRIM(@tday))
set @ftime=RTRIM(LTRIM(@ftime))
set @ttime=RTRIM(LTRIM(@ttime))
set @sh_kargozini=RTRIM(LTRIM(@sh_kargozini))
set @code_ertebat=RTRIM(LTRIM(@code_ertebat))
set @code_shift_str=RTRIM(LTRIM(@code_shift_str))
set @code_bimeh_str=RTRIM(LTRIM(@code_bimeh_str))
set @code_bakhsh_str=RTRIM(LTRIM(@code_bakhsh_str))
set @code_pezeshk_str=RTRIM(LTRIM(@code_pezeshk_str))


    if ( (LEN(@fday)=10) and (LEN(@tday)=10))
	begin


    select * from morajeat where tarikh between @fday and @tday

	end
	else
	select 0 as s_result, ':( no condition to run sp : '+OBJECT_NAME(@@PROCID) as s_message ,' no param '+OBJECT_NAME(@@PROCID) as s_param


end
GO




CREATE procedure [dbo].[_2227_R_Vaght_Dehi_User_Insert]
(
@fday char(10),
@tday char(10),
@ftime char(20),
@ttime char(20),
@code_user int,
@code_shift	int,
@code_shobeh int,
@code_pay int,
@code_bimeh int,
@code_bakhsh int,
@code_pezeshk int,
@code_dastyar int,
@code_darman int,
@code_bimar int,
@code_ranandeh int,
@code_yaraneh int,
@code_mokammel	int,
@sh_kargozini varchar(20),
@code_ertebat	varchar(20),
@code_shift_str	varchar(500),
@code_bimeh_str	varchar(500),
@code_bakhsh_str varchar(500),
@code_pezeshk_str varchar(500),
@lucp int
)
as
begin

set @fday=RTRIM(LTRIM(@fday))
set @tday=RTRIM(LTRIM(@tday))
set @ftime=RTRIM(LTRIM(@ftime))
set @ttime=RTRIM(LTRIM(@ttime))
set @sh_kargozini=RTRIM(LTRIM(@sh_kargozini))
set @code_ertebat=RTRIM(LTRIM(@code_ertebat))
set @code_shift_str=RTRIM(LTRIM(@code_shift_str))
set @code_bimeh_str=RTRIM(LTRIM(@code_bimeh_str))
set @code_bakhsh_str=RTRIM(LTRIM(@code_bakhsh_str))
set @code_pezeshk_str=RTRIM(LTRIM(@code_pezeshk_str))


    if ( (LEN(@fday)=10) and (LEN(@tday)=10))
	begin


    select * from vaght_dehi where tarikh between @fday and @tday

	end
	else
	select 0 as s_result, ':( no condition to run sp : '+OBJECT_NAME(@@PROCID) as s_message ,' no param '++OBJECT_NAME(@@PROCID) as s_param


end
GO




CREATE procedure [dbo].[_2228_R_Morajeat_SUM_shift]
(
@fday char(10),
@tday char(10),
@ftime char(20),
@ttime char(20),
@code_user int,
@code_shift	int,
@code_shobeh int,
@code_pay int,
@code_bimeh int,
@code_bakhsh int,
@code_pezeshk int,
@code_dastyar int,
@code_darman int,
@code_bimar int,
@code_ranandeh int,
@code_yaraneh int,
@code_mokammel	int,
@sh_kargozini varchar(20),
@code_ertebat	varchar(20),
@code_shift_str	varchar(500),
@code_bimeh_str	varchar(500),
@code_bakhsh_str varchar(500),
@code_pezeshk_str varchar(500),
@lucp int
)
as
begin

set @fday=RTRIM(LTRIM(@fday))
set @tday=RTRIM(LTRIM(@tday))
set @ftime=RTRIM(LTRIM(@ftime))
set @ttime=RTRIM(LTRIM(@ttime))
set @sh_kargozini=RTRIM(LTRIM(@sh_kargozini))
set @code_ertebat=RTRIM(LTRIM(@code_ertebat))
set @code_shift_str=RTRIM(LTRIM(@code_shift_str))
set @code_bimeh_str=RTRIM(LTRIM(@code_bimeh_str))
set @code_bakhsh_str=RTRIM(LTRIM(@code_bakhsh_str))
set @code_pezeshk_str=RTRIM(LTRIM(@code_pezeshk_str))


    if ( (LEN(@fday)=10) and (LEN(@tday)=10))
	begin


     select code_shift,
	(select name_shift from shiftha where code_shift=m.code_shift) as name_shift,
	sum(r_bes) as daryafti from morajeat m where tarikh between @fday and  @tday group by code_shift

	end
	else
	select 0 as s_result, ':( no condition to run sp : '+OBJECT_NAME(@@PROCID) as s_message ,' no param '+OBJECT_NAME(@@PROCID) as s_param


end
GO




CREATE procedure [dbo].[_2229_R_Morajeat_SUM_pezeshk]
(
@fday char(10),
@tday char(10),
@ftime char(20),
@ttime char(20),
@code_user int,
@code_shift	int,
@code_shobeh int,
@code_pay int,
@code_bimeh int,
@code_bakhsh int,
@code_pezeshk int,
@code_dastyar int,
@code_darman int,
@code_bimar int,
@code_ranandeh int,
@code_yaraneh int,
@code_mokammel	int,
@sh_kargozini varchar(20),
@code_ertebat	varchar(20),
@code_shift_str	varchar(500),
@code_bimeh_str	varchar(500),
@code_bakhsh_str varchar(500),
@code_pezeshk_str varchar(500),
@lucp int
)
as
begin

set @fday=RTRIM(LTRIM(@fday))
set @tday=RTRIM(LTRIM(@tday))
set @ftime=RTRIM(LTRIM(@ftime))
set @ttime=RTRIM(LTRIM(@ttime))
set @sh_kargozini=RTRIM(LTRIM(@sh_kargozini))
set @code_ertebat=RTRIM(LTRIM(@code_ertebat))
set @code_shift_str=RTRIM(LTRIM(@code_shift_str))
set @code_bimeh_str=RTRIM(LTRIM(@code_bimeh_str))
set @code_bakhsh_str=RTRIM(LTRIM(@code_bakhsh_str))
set @code_pezeshk_str=RTRIM(LTRIM(@code_pezeshk_str))


    if ( (LEN(@fday)=10) and (LEN(@tday)=10))
	begin


     select code_pezeshk,
	(select name_pezeshk from pezeshkan where code_pezeshk=m.code_pezeshk) as name_pezeshk,
	sum(r_bes) as r_bes,sum(r_mokammel) as r_mokammel from morajeat m where tarikh between @fday and  @tday group by code_pezeshk

	end
	else
	select 0 as s_result, ':( no condition to run sp : '+OBJECT_NAME(@@PROCID) as s_message ,' no param '+OBJECT_NAME(@@PROCID) as s_param


end
GO

-- 1399/01/26
-- restricted_code_bakhshha
ALTER TABLE [dbo].[users]
   add [restricted_code_anbarha] varchar(200) NULL 
Go


Go
----------------------------------------------------------
 Go
delete auto_sms where (SendAnswer <= 0) 
and( tarikh < '1399/01/26') 
and (sdate is null or sdate < '1399/01/26')
Go
-- update settingc set start_tarikh_takhfif_etebari='1398/10/12'
Go
update setting set version=13970418
Go

-- copy_file copy_image from_drive
-- Simple Image Import and Export Using T-SQL for SQL Server
Use master
Go
EXEC sp_configure 'show advanced options', 1; 
GO 
RECONFIGURE; 
GO 
EXEC sp_configure 'Ole Automation Procedures', 1; 
GO 
RECONFIGURE; 
GO
--ALTER SERVER ROLE [bulkadmin] ADD MEMBER [Enter here the Login Name that will execute the Import] 
--ALTER SERVER ROLE [bulkadmin] ADD MEMBER [sa] 
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [acp\Administrator] 
GO  
--USE [master]
GO
--CREATE USER [acp\Administrator] FOR LOGIN [acp\Administrator]
 

--- job script
--  Job [test_job] 
GO

USE [msdb]
GO

/****** Object:  Job [test_job]    Script Date: 2019/11/19 14:05:27 ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 2019/11/19 14:05:27 ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'test_job', 
		@enabled=1, 
		@notify_level_eventlog=0, 
		@notify_level_email=0, 
		@notify_level_netsend=0, 
		@notify_level_page=0, 
		@delete_level=0, 
		@description=N'sample to insert test_table with sp                                               insert test_table (in_date,tcounter) values (GETDATE(), @i)', 
		@category_name=N'[Uncategorized (Local)]', 
		@owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [step 1]    Script Date: 2019/11/19 14:05:27 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'step 1', 
		@step_id=1, 
		@cmdexec_success_code=0, 
		@on_success_action=1, 
		@on_success_step_id=0, 
		@on_fail_action=2, 
		@on_fail_step_id=0, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'exec sp_test_job_insert_test_table', 
		@database_name=N'Darmangah', 
		@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'everey_min', 
		@enabled=1, 
		@freq_type=4, 
		@freq_interval=1, 
		@freq_subday_type=8, 
		@freq_subday_interval=23, 
		@freq_relative_interval=0, 
		@freq_recurrence_factor=0, 
		@active_start_date=20191119, 
		@active_end_date=99991231, 
		@active_start_time=0, 
		@active_end_time=235959, 
		@schedule_uid=N'f0288a64-0ee9-4651-8e98-1927237cd4d3'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO

USE [msdb]
GO

/****** Object:  Job [job_transfer_all_bimaran_to_Ezdenti]    Script Date: 2019/11/19 14:06:07 ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 2019/11/19 14:06:07 ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'job_transfer_all_bimaran_to_Ezdenti', 
		@enabled=1, 
		@notify_level_eventlog=0, 
		@notify_level_email=0, 
		@notify_level_netsend=0, 
		@notify_level_page=0, 
		@delete_level=0, 
		@description=N'test test', 
		@category_name=N'[Uncategorized (Local)]', 
		@owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [1]    Script Date: 2019/11/19 14:06:07 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'1', 
		@step_id=1, 
		@cmdexec_success_code=0, 
		@on_success_action=1, 
		@on_success_step_id=0, 
		@on_fail_action=2, 
		@on_fail_step_id=0, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'exec transfer_all_bimaran_to_Ezdenti', 
		@database_name=N'Darmangah', 
		@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'5_min', 
		@enabled=1, 
		@freq_type=4, 
		@freq_interval=1, 
		@freq_subday_type=4, 
		@freq_subday_interval=23, 
		@freq_relative_interval=0, 
		@freq_recurrence_factor=0, 
		@active_start_date=20191118, 
		@active_end_date=99991231, 
		@active_start_time=0, 
		@active_end_time=235959, 
		@schedule_uid=N'f810bd0e-c78c-41ce-b6ce-4193903455d6'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO



























-- update settingb set show_Not_Finished=1

--  update setting set not_finished_defult_Morajeat=1

--old version--  update setting set version=940510

-- update settingc set show_r_labratvar2_paziresh=1

-- update settingc set negetive_r_mabeh=1
-- for clinic sabz

--  check_Active_Bimar_for_Vaghtdehi

-- update settingb set check_Active_Bimar_for_Vaghtdehi=1

-- update settingb set check_Active_Bimar_for_Paziresh=1

-- drop table settingc

/*

DECLARE @mywhere VARCHAR(500)
DECLARE @mystmt VARCHAR(1000)
SET @mywhere = ' WHERE MfgPartNumber LIKE ''a%'' '
SELECT @mystmt = 'SELECT TOP 100 * FROM Products.Product AS p ' + @mywhere + ';'
EXEC( @mystmt )

*/

/*
CREATE PROCEDURE [dbo].[myProc]
@whereSql nvarchar(256)

AS
    EXEC('SELECT [fields] FROM [table] WHERE ' + @whereSql)


*/

/*
شرط
برای  ارسال پیامک نکات بهداشتی برای هر درمان و سایر موارد 
  if (Q_setting.fieldbyname('SMS_Tarikh_Tavalod').AsBoolean) and
    (SecondOf(now) = 40) and (MinuteOf(now) mod 20 = 0) and
    (TIME_NOW >= Q_setting.fieldbyname('SMS_Tarikh_Tavalod_Time_From').AsString)
    and (TIME_NOW <= Q_setting.fieldbyname('SMS_Tarikh_Tavalod_Time_To')
    .AsString) and (Auto_Send_SMS) thenselect top 10 * from auto_sms where 1 > 0 

 select top 10 * from auto_sms where 1 > 0 
 and '1397/07/03' between sdate and edate  
 and '23:20' between stime and etime  
 and code_babat=34
 and len(SMS_Mobile)>= 11 and SMS_Mobile like '09%'
 and SendAnswer < 1 
 order by id DESC
  
  جستجوی نوع خاص  فیلد در کل دیتا بیس

 SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where data_type = 'NTEXT'

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where data_type = 'bit' and table_name like 'setting%' 


SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
table_name like 'setting%'   and 
column_name like '%show%'

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
table_name like 'setting%'   and 
column_name like '%sms%' 

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
table_name like 'setting%'   and 
column_name like '%moaref%'


SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
data_type = 'bit' and 
column_name like '%moaref%'

جستجوی  فیلد در کل دیتا بیس
SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
column_name like '%moaref%'


SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where 
column_name like '%code_ertebat%'


*/
--  Search for one value in any column of any table inside a database
--  exec SearchAllTables 'معرف'

/*

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results
 END

*/
