 /*
		Firma 

UpdateFirma script

Martie 23, 2011
Version 1.0 
----------------------------------
	- Se face dupa ce se logheaza pe o firma!
	- If Exists (Select 1 From sys.objects o Where o.name =’TableName’ And o.type =’U’)
	- IF Object_id('dbo.Special') IS NOT NULL

*/

GO

/*Update#20110930.sql*/
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='MijloaceFixe' AND COLUMN_NAME='ContChelt')
	ALTER TABLE [dbo].[MijloaceFixe] ADD [ContChelt] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Amortizari' AND COLUMN_NAME='ContChelt')
	ALTER TABLE [dbo].[Amortizari] ADD [ContChelt] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Registru' AND COLUMN_NAME='IdTva')
	ALTER TABLE [dbo].[Registru] ADD [IdTva] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='CodValuta')
	ALTER TABLE [ComenziTransport].[Comenzi] ADD [CodValuta] char(3) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='Curs')
	ALTER TABLE [ComenziTransport].[Comenzi] ADD [Curs] numeric(14, 4) NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='D390' AND COLUMN_NAME='Cod')
	ALTER TABLE [Declaratii].[D390] ALTER COLUMN [Cod] char(20) COLLATE Latin1_General_CI_AS
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='IntrariDetaliat' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[IntrariDetaliat] ADD [IdLot] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='IesiriDetaliat' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[IesiriDetaliat] ADD [IdLot] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Import' AND COLUMN_NAME='BazaTva')
	ALTER TABLE [dbo].[Import] ADD [BazaTva] numeric(14, 2) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportDetaliat' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[ImportDetaliat] ADD [IdLot] int NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='NumarDoc')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [NumarDoc] char(16) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Cont')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [Cont] char(20) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='ValoareValuta')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [ValoareValuta] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='ValoareLei')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [ValoareLei] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Total')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [Total] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='NeachitatLei')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [NeachitatLei] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='NeachitatValuta')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [NeachitatValuta] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Tip')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [Tip] char(1) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Validat')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [Validat] char(1) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Tva')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [Tva] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Denumire')
	ALTER TABLE [dbo].[ImportTransport] ALTER COLUMN [Denumire] char(48) COLLATE Latin1_General_CI_AS
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ExportDetaliat' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[ExportDetaliat] ADD [IdLot] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='NotePredareDetaliat' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[NotePredareDetaliat] ADD [IdLot] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='BonuriConsumDetaliat' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[BonuriConsumDetaliat] ADD [IdLot] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Articole' AND COLUMN_NAME='IsLot')
	ALTER TABLE [dbo].[Articole] ADD [IsLot] bit DEFAULT 0 NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ItemsTransactions' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[ItemsTransactions] ADD [IdLot] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ItemsDischarge' AND COLUMN_NAME='IdLot')
	ALTER TABLE [dbo].[ItemsDischarge] ADD [IdLot] int NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='IdComanda')
	EXEC sp_rename '[dbo].[Comenzi].[IdComanda]', 'IdComandaTert', 'COLUMN'
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ComenziDetaliat' AND COLUMN_NAME='IdUnicComanda')
	EXEC sp_rename '[dbo].[ComenziDetaliat].[IdUnicComanda]', 'IdComanda', 'COLUMN'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Amortizari' AND COLUMN_NAME='IsConservat')
	ALTER TABLE [dbo].[Amortizari] ADD [IsConservat] bit DEFAULT 0 NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Amortizari' AND COLUMN_NAME='Plan_A')
	EXEC sp_rename '[dbo].[Amortizari].[Plan_A]', 'PlanB', 'COLUMN'
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Amortizari' AND COLUMN_NAME='Capitol')
	EXEC sp_rename '[dbo].[Amortizari].[Capitol]', 'CapitolB', 'COLUMN'
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Amortizari' AND COLUMN_NAME='Articol')
	EXEC sp_rename '[dbo].[Amortizari].[Articol]', 'ArticolB', 'COLUMN'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='AmortizariDetaliat' AND COLUMN_NAME='DataIesireConservare')
	ALTER TABLE [dbo].[AmortizariDetaliat] ADD [DataIesireConservare] date NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Registru' AND COLUMN_NAME='ContD')
	ALTER TABLE [dbo].[Registru] ALTER COLUMN [ContD] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Registru' AND COLUMN_NAME='ContC')
	ALTER TABLE [dbo].[Registru] ALTER COLUMN [ContC] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF Object_id('dbo.ActivitatiUtilizatori') IS NOT NULL
	DROP TABLE [dbo].[ActivitatiUtilizatori]
GO

IF Object_id('Configurari.Trezorerie') IS NOT NULL
	DROP TABLE [Configurari].[Trezorerie]
GO

IF Object_id('dbo.ArtGest') IS NOT NULL
	DROP TABLE [dbo].[ArtGest]
GO

IF Object_id('dbo.Retineri') IS NOT NULL
	DROP TABLE [dbo].[Retineri]
GO

IF Object_id('dbo.Tichete') IS NOT NULL
	DROP TABLE [dbo].[Tichete]
GO

IF EXISTS(SELECT * FROM sys.views WHERE name = 'vArticoleInventar' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.vArticoleInventar
GO

CREATE View vArticoleInventar
	AS
	SELECT 
		a.Denumire AS Articol,
		a.Um,
		g.CONT,
		g.id AS IDGest,
		g.denumire AS DenGest, 
		ta.Stocabil,
		a.Pret_Aman AS PretAmanunt,
		a.Id,
		a.Tva As ProcTva, 
		ta.Denumire As DenTipArt,
		ta.Id As IdTipArt
	FROM Articole a
		INNER JOIN Gestiuni g 
			ON g.Id = A.IdGest
		INNER JOIN TipuriArticole ta 
			ON ta.Id =a.IdTipArt
	WHERE Stocabil = 1
GO

IF EXISTS(SELECT * FROM sys.views WHERE name = 'ArticoleIesire' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.ArticoleIesire
GO

Create View ArticoleIesire As 
Select
	ta.Denumire As DenTipArt, 
    ta.Id As IdTipArt, 
	g.Cont As Cont,   
	--Case When g.Tip_Gest = 'Cantitativ-Valorica' Then ta.ContVenit Else g.glob_707 End As ContVGest,
    g.glob_707 As ContVGest, 
    IsNull(Stocabil, 0) As Stocabil, 
    g.Denumire As DenGest, 
    g.Id As IdGest, 
    g.TipEval,
    Case When g.Tip_Gest = 'Cantitativ-Valorica' Then a.Denumire Else 'Marfuri' End As Denumire,
    Case When g.Tip_Gest = 'Cantitativ-Valorica' Then a.Id Else Null End As Id,    
    Case When g.Tip_Gest = 'Cantitativ-Valorica' Then a.Pret_Aman Else Null End As PretAmanunt,    
    Case When g.Tip_Gest = 'Cantitativ-Valorica' Then a.Tva Else 24 End As ProcTva,        
    Case When g.Tip_Gest = 'Cantitativ-Valorica' Then a.Um Else 'Buc' End As Um,
    Case When IsNull(Stocabil,0)=1 Then a.Stoc Else 0 End As Stoc,
	Null As IdMf
From Gestiuni g
	Left Join TipuriArticole ta On g.IdTipArt = ta.Id
    Inner Join Articole a On a.IdTipArt = ta.Id    
	Where
    	IsNull(ta.Vandabil, 0) = 1 
        And IsNull(ta.Sters, 0) = 0
Union
Select
	ta.Denumire As DenTipArt, 
    ta.Id As IdTipArt, 
	ta.Cont As Cont,   
    ta.ContVenit As ContVGest, 
    IsNull(Stocabil, 0) As Stocabil, 
    Null As DenGest, 
    Null As IdGest, 
    Null As TipEval,
    a.Denumire As Denumire,
    a.Id As Id,    
    a.Pret_Aman As PretAmanunt,    
    a.Tva As ProcTva,        
    a.Um As Um,
    Case When IsNull(Stocabil,0)=1 Then a.Stoc Else 0 End As Stoc,
    Null As IdMf   
From TipuriArticole ta 
    Inner Join Articole a On a.IdTipArt = ta.Id    
	Where
    	IsNull(ta.Vandabil, 0) = 1 
        And IsNull(ta.Sters, 0) = 0
Union
Select
	ta1.Denumire As DenTipArt, 
    ta1.Id As IdTipArt,
    ta1.Cont,
    Coalesce( Case When ta1.ContVenit='' Then c.Cont Else ta1.ContVenit End, ta1.Cont) As ContVGest, 
	IsNull(Stocabil,0) As Stocabil,
    Null As DenGest, 
	Null As IdGest, 
	Null As TipEval,
    c.Denumire, 
	Null As Id, 
	Null As PretAmanunt, 
    24 As ProcTva, 
    'Buc' As Um ,
    0 As Stoc,
	Null As IdMf
From TipuriArticole ta1  
	Inner Join Conturi c On c.Cont = ta1.Cont
	Where
		IsNull(ta1.Vandabil, 0) = 1 
        And IsNull(ta1.Sters, 0) = 0
Union
Select
	Null As DenTipArt,
	Null As IdTipArt,
	Null As Cont,
    dl.Cont As ContVGest, 
    Cast(0 As Bit) As Stocabil,
	Null As DenGest, 
	Null As IdGest, 
	Null As TipEval,     
    dl.Denumire,
	Null As Id,
    dl.PretUnitar As PretAmanunt,
    dl.ProcTva,
    dl.Um,
    0 As Stoc,
	Null As IdMf
From IesiriDetaliat dl
	Where IsNull(IdArticol, 0) = 0
    Group By Denumire, PretUnitar, Cont, Um, IdArticol, ProcTva
Union
Select
	'Mijloace Fixe' As DenTipArt,
	13 As IdTipArt, 
	mf.Cont As Cont,
	'7583' As ContVGest,    
    Cast(0 As Bit) As Stocabil,    
	Null As DenGest,
	Null As IdGest,
	Null As TipEval,    
   	mf.Denumire As Denumire,
	mf.Id As Id,     
	Null As PretAmanunt, 
    24 As ProcTva, 
    'Buc' As Um ,
    0 As Stoc,
	mf.Id As IdMf
From MijloaceFixe mf
GO

IF EXISTS(SELECT * FROM sys.views WHERE name = 'ArticoleFacturiIesire' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.ArticoleFacturiIesire
GO

Create View ArticoleFacturiIesire As 
Select
	a.Denumire As Articol,
    a.Um, 
	-- Case When g.Tip_Gest = 'Cantitativ-Valorica' Then ta.ContVenit Else g.glob_707 End As Cont, 
	g.Glob_707 As Cont, 
	g.id As IdGest, 
    g.Denumire As DenGest, 
    g.TipEval, 
	ta.Stocabil, 
    a.Pret_Aman As PretAmanunt, 
    a.Id, 
    a.Tva As ProcTva, 
	ta.Denumire As DenTipArt, 
    ta.Id As IdTipArt
From Articole a
	Inner Join Gestiuni g On g.id = a.IdGest
	Inner Join TipuriArticole ta On Left(ta.Cont,3)=Left(g.Cont,3) 
	Where
    	IsNull(ta.Vandabil, 0) = 1  
        And IsNull(Stocabil, 0) In (0,  1)
Union
Select
	Coalesce (ta1.Denumire, c.Denumire) As Articol, 
	'buc' As Um, 
    Coalesce(Case When ta1.ContVenit='' Then c.Cont Else ta1.ContVenit End, ta1.Cont) As Cont, 
    Null As IdGest, 
    Null As DenGest, 
    Null As TipEval,     
	IsNull(ta1.Stocabil, Convert(Bit, 0)) As Stocabil, 
    0 As PretAmanunt, 
    0 As Id, 
    24 AS ProcTva, 
	IsNull(ta1.Denumire, 'Venituri') As DenTipArt,
    IsNull(ta1.Id, 0) As IdTipArt
From TipuriArticole ta1  
	Inner Join Conturi c On c.Cont = ta1.Cont
	Where
    	IsNull(ta1.Vandabil, 0) = 1 
        And IsNull(Stocabil, 0) = 0
Union
Select
	dl.Denumire,
    dl.Um, 
    dl.Cont, 
    Null As IdGest, 
    Null As DenGest, 
    Null As TipEval,     
    Cast(0 As Bit) As Stocabil, 
    Cast(0 As Decimal(10,4)) As PretAmanunt, 
    IdArticol As Id, 
    ProcTva, 
    Cast('' As VarChar(36)) As DenTipArt ,
    Cast(0 As Int) As IdTipArt 
From ExportDetaliat dl
	Where IsNull(IdArticol, 0) = 0
    Group By Denumire, Cont, Um, IdArticol, ProcTva
GO

IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'Declaratii')
	EXECUTE ('CREATE SCHEMA Declaratii AUTHORIZATION dbo;')
GO

IF Object_id('dbo.ConturiBalantaMixte') IS NULL
CREATE TABLE [dbo].[ConturiBalantaMixte] (
  [id] int IDENTITY(1, 1) NOT NULL,
  [IdCont] int NULL,
  [Created] datetime CONSTRAINT [ConturiBalantaMixte_Created_df] DEFAULT getdate() NOT NULL,
  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [ConturiBalantaMixte_CreatedBy_df] DEFAULT suser_sname() NULL,
  [Modified] datetime CONSTRAINT [ConturiBalantaMixte_Modified_df] DEFAULT getdate() NOT NULL,
  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [ConturiBalantaMixte_ModifiedBy_df] DEFAULT suser_sname() NULL,
  [RowVersion] int CONSTRAINT [ConturiBalantaMixte_RowVersion_df] DEFAULT 1 NOT NULL,
  PRIMARY KEY CLUSTERED ([id]),
  UNIQUE ([IdCont])
)
ON [PRIMARY]
GO

IF Object_id('dbo.Cec') IS NULL
    CREATE TABLE [dbo].[Cec] (
      [Id] int NOT NULL,
      [Scadenta] date NULL,
      [ContPart] char(20) COLLATE Latin1_General_CI_AS NULL,
      [DenPart] char(50) COLLATE Latin1_General_CI_AS NULL
    )
    ON [PRIMARY]
GO

IF Not EXISTS ( SELECT t.name AS [Table Name], ex.value AS Description 
				FROM sys.tables AS t, sys.extended_properties AS ex
				WHERE 
					ex.major_id = t.object_id 
					AND ex.name = 'MS_Description' 
					AND t.Name = 'Cec' 
					AND Value  = 'Este id-ul Din registru(Id_Note)')
                    
    EXEC sp_addextendedproperty 'MS_Description', N'Este id-ul Din registru(Id_Note)', 'schema', 'dbo', 'table', 'Cec', 'column', 'Id'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='IdUnic')
	ALTER TABLE dbo.ImportTransport ADD [IdUnic] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Valuta' AND COLUMN_NAME='Curs_An')
	ALTER TABLE [dbo].[Valuta] ADD [Curs_An] decimal(9, 4) NULL
GO

IF Object_id('Declaratii.F101') IS NULL
CREATE TABLE [Declaratii].[F101] (
  [Id] int IDENTITY(1, 1) NOT NULL,
  [Indicator] char(240) COLLATE Latin1_General_CI_AS NOT NULL,
  [Nr] int NOT NULL,
  [Nr_nou] int NOT NULL,
  [An_c] numeric(4, 0) NULL,
  [Exp] text COLLATE Latin1_General_CI_AS NOT NULL,
  [Err] bit DEFAULT 0 NULL,
  CONSTRAINT [F101_pk] PRIMARY KEY CLUSTERED ([Id])
)
ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='F101' AND COLUMN_NAME='Indicator')
	ALTER TABLE [Declaratii].[F101] ALTER COLUMN [Indicator] char(240) COLLATE Latin1_General_CI_AS NOT NULL
ELSE
	ALTER TABLE [Declaratii].[F101] ADD [Indicator] char(240) COLLATE Latin1_General_CI_AS NOT NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='F101' AND COLUMN_NAME='Nr')
	ALTER TABLE [Declaratii].[F101] ALTER COLUMN [Nr] int NOT NULL
ELSE
	ALTER TABLE [Declaratii].[F101] ADD [Nr] int NOT NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='F101' AND COLUMN_NAME='Nr_Nou')
	ALTER TABLE [Declaratii].[F101] ALTER COLUMN [Nr_Nou] int NOT NULL
ELSE
	ALTER TABLE [Declaratii].[F101] ADD [Nr_Nou] int NOT NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='F101' AND COLUMN_NAME='An_c')
	ALTER TABLE [Declaratii].[F101] ALTER COLUMN [An_c] numeric(4, 0) NULL
ELSE
	ALTER TABLE [Declaratii].[F101] ADD [An_c] numeric(4, 0) NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='F101' AND COLUMN_NAME='Exp')
	ALTER TABLE [Declaratii].[F101] ALTER COLUMN [Exp] text COLLATE Latin1_General_CI_AS NOT NULL
ELSE
	ALTER TABLE [Declaratii].[F101] ADD [Exp] text COLLATE Latin1_General_CI_AS NOT NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='F101' AND COLUMN_NAME='Err')
	ALTER TABLE [Declaratii].[F101] ALTER COLUMN [Err] bit NULL
ELSE
	ALTER TABLE [Declaratii].[F101] ADD [Err] bit DEFAULT 0 NULL
GO

Truncate TABLE [Declaratii].[F101]
GO

/* Data for the 'Declaratii.F101' table  (Records 1 - 61) */

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Venituri din exploatare', 1, 1, NULL, N'(701, c) + (702, c) + (703, c) + (704, c) + (705, c) + (706, c) + (708, c) - (709, d)  + (707, c) + (7411, c)  + (721, c) + (722, c) + (7417, c) + (758, c)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli de exploatare', 2, 2, NULL, N'(601, d) + (602, d) + (603, d) + (604, d) + (606, d) + (608, d)  - (609, c) + (605, d) + (607, d) + (641, d)+(642 ,d) + (645, d) + (6811, d)  + (6813, d)  - (7813, c) + (654,d) + (6814,d) - (754,c) - (7814,c) + (611, d) + (612, d) + (613, d) + (614, d) + (621, d) + (622, d) + (623, d) + (624, d) + (625, d) + (626, d) + (627, d) + (628, d)  + (635, d) + (658, d) + (6812,d) + (691, d) - (7812,c)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Rezultat din exploatare (rd.1 - rd.2)', 3, 3, NULL, N'r1 - r2', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Venituri financiare', 4, 4, NULL, N'(7611, c) + (7613, c) + (763, c) + (766, c) + (762,c) + (764,c) + (765,c) + (767,c) + (768,c)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli financiare', 5, 5, NULL, N'(686, d)  - (786, c)  + (666, d)  + (663, d) + (664, d) + (665, d)  + (667, d) + (668, d)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Rezultat  financiar (rd.4 - rd.5)', 6, 6, NULL, N'r4 - r5', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Venituri extraordinare', 7, 7, NULL, N'(771, c)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli extraordinare', 8, 8, NULL, N'(671, d)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Rezultat extraordinar (rd.7 - rd.8)', 9, 9, NULL, N'r7 - r8', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Rezultat brut (rd.3 + rd.6 + rd.9)', 10, 10, NULL, N'r3 + r6 + r9', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Elemente similare veniturilor', 11, 11, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Elemente similare cheltuielilor', 12, 12, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Rezultat dupa includerea elementelor similare veniturilor/cheltuielilor (rd.10 + rd.11 - rd.12)', 13, 13, NULL, N'r10 + r11 - r12', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Amortizare fiscala', 14, 14, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu dobânzile si diferentele de curs valutar reportate din perioada precedenta', 15, 15, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Rezerva legala deductibila', 16, 16, NULL, N'(1061,c)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Provizioane fiscale', 17, 17, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Alte sume deductibile, din care:', 18, 18, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Deduceri suplimentare pentru cercetare-dezvoltare', 181, 181, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Total deduceri (rd.14 la rd.18)', 19, 19, NULL, N'r14 + r15 + r16 + r17 + r18', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Dividende primite de la alta persoana juridica româna', 20, 20, NULL, N'(761,c)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Alte venituri neimpozabile', 21, 21, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Total venituri neimpozabile (rd.20 + rd.21)', 22, 22, NULL, N'r20 + r21', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Profit/pierdere (rd.13 - rd.19 - rd.22)', 23, 23, NULL, N'r13 - r19 -r22', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu impozitul pe profit', 24, 24, NULL, N'(691, d)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu impozitul pe profitul/ venitul realizat in strainatate', 25, 25, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Dobanzile/majorarile de intarziere, amenzile, confiscarile si penalitati de intârziere datorate catre autoritatile române sau straine', 26, 26, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli de protocol care depasesc limita prevazuta de lege', 27, 27, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli de sponsorizare si/sau mecenat, burse private, efectuate potrivit legii', 28, 28, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu amortizarea contabila', 29, 29, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu  provizioanele si cu rezervele care depasesc limita prevazuta de lege', 30, 30, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu dobânzile nedeductibile, care nu sunt reportate pentru perioada următoare', 31, 31, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli cu dobânzi si diferente de curs valutar reportate pentru perioada urmatoare', 32, 32, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Cheltuieli aferente veniturilor neimpozabile', 33, 33, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Alte cheltuieli nedeductibile', 34, 34, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Total cheltuieli nedeductibile (rd. 24 la rd. 34)', 35, 35, NULL, N'r24 + r25 +r26+r27+r28+r29+r30+r31+r32+r33+r34', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Total profit impozabil/ pierdere fiscala pentru anul de raportare, inainte de reportarea pierderii (rd.23 + rd.35)', 36, 36, NULL, N'r23+r35', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Pierdere fiscală în perioada curentă, de reportat pentru perioada următoare', 37, 37, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Pierdere fiscala de recuperat din anii precedenti', 38, 38, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Profit impozabil/Pierdere fiscală, de recuperat în anii următori (rd.36+rd.37-rd.38)', 39, 39, NULL, N'r36+r37-r38', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Total impozit pe profit (rd.40.1 la rd.40.2) din care:', 40, 40, NULL, N'r401+r402', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit aferent profitului ce se impune cu cota de 16%', 401, 401, NULL, N'max(r39*16/100,0)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit de 5% aplicat veniturilor din activita!i de natura barurilor de noapte, cluburilor de noapte, a discotecilor si a cazinourilor sau pariurilor sportive', 402, 402, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Total credit fiscal(rd.41.1+41.2+ rd.41.3.)', 41, 41, NULL, N'r411+r412+r413', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Credit fiscal extern', 411, 411, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit scutit, din care:', 412, 412, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit scutit, potrivit art.38 alin.(1) si alin.(8) din Codul fiscal', 4121, 4121, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit scutit, potrivit art.19^2 din Codul fiscal', 4122, 4122, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N' Scutiri si reduceri de impozit pe profit calculate potrivit legislatiei in vigoare', 413, 413, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit inainte de scaderea sumelor reprezentand sponsorizare si/sau mecenat si burse private (rd. 40 - rd. 41) >=0', 42, 42, NULL, N'r40-r41', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Sume repr.sponsorizare si/sau mecenat, burse private, in limita prev.de lege', 43, 43, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit datorat anual (rd.41-rd.43)>=0', 44, 44, NULL, N'max(r42-r43,0)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit anual (se preia suma de la rd.44)', 101, 1, NULL, N'r42-r43', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit aferent activitatilor de natura barurilor de noapte, cluburilor de noapte,a discotecilor si a cazinourilor sau pariurilor sportive', 1011, 11, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit aferent altor activitati decat cele de la rd.1.1 (rd.1-rd.1.1)', 1012, 12, NULL, N'r101-r1011', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit minim', 102, 2, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit datorat ( 1.1 + 1.2, daca rd.1.2 >= rd.2 sau 1.1 + 2, daca rd.1.2 < rd.2 )', 103, 3, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit stabilit în urma inspectiei fiscale pentru anul fiscal de raportare si care se regaseste in indicatorii din formular', 104, 4, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Impozit pe profit declarat pentru anul de raportare prin formularul 100', 105, 5, NULL, N'', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Diferenta de impozit pe profit datorat [ rd.3 - ( rd.4 + rd.5) ]', 106, 6, NULL, N'max(r103-r104-r105,0)', 0)
GO

INSERT INTO [Declaratii].[F101] ([Indicator], [Nr], [Nr_nou], [An_c], [Exp], [Err])
VALUES (N'Diferenta de impozit pe profit de recuperat [ ( rd.4 + rd.5) - rd.3 ]', 107, 7, NULL, N'max(r104+r105-r103,0)', 0)
GO

IF Object_id('Declaratii.D100') IS NULL
	CREATE TABLE [Declaratii].[D100] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Cod_Bug] char(10) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Nr_Evid3] numeric(3, 0) NOT NULL,
	  [Cod] numeric(3, 0) NOT NULL,
	  [Denumire] char(100) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Beneficiar] char(48) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Ok] numeric(1, 0) NOT NULL,
	  [Is_Rec] bit NOT NULL,
	  [Is_Cu_Ob] bit NOT NULL,
	  [Is_ImpM] bit NOT NULL,
	  CONSTRAINT [D100_pk] PRIMARY KEY CLUSTERED ([Id])
	)
	ON [PRIMARY]
GO

ALTER TABLE [Declaratii].[D100] ALTER COLUMN [Ok] numeric(1, 0)
GO

Truncate TABLE [Declaratii].[D100]
GO

/* Data for the 'Declaratii.D100' table  (Records 1 - 25) */

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 102, 1, N'102--Plati anticipate, in contul impozitului pe profit anul - banci', N'BUGET DE STAT', 0, 0, 1, 1)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 103, 2, N'103--Imp.pe profit datorat de PJ romane', N'BUGET DE STAT', 0, 0, 1, 1)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 106, 3, N'106--Imp.pe profit din asociere datorat de PF', N'BUGET DE STAT', 0, 1, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 105, 4, N'105--Imp.pe profit datorat de PJ straine', N'BUGET DE STAT', 0, 1, 1, 1)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 150, 5, N'150--Imp.pe dividende distribuite la PJ', N'BUGET DE STAT', 0, 0, 1, 1)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 121, 6, N'121--Imp.pe ven. microintreprinderilor', N'BUGET DE STAT', 0, 1, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 122, 7, N'122--Imp.pe ven. PF dintr-o asociere cu o PJ microintreprindere', N'BUGET DE STAT', 0, 0, 1, 1)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 611, 8, N'611--Imp.pe ven.- drepturi de prop.intelectuala', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 615, 9, N'615--Imp.pe ven.- expertiza contabila si tehnica,judiciara si extrajudiciara', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 616, 10, N'616--Imp.pe ven.- contracte/conventii civile', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 614, 11, N'614--Imp.pe ven.- consignatie/contract agent/comision/mandat comercial', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 604, 12, N'604--Imp.pe ven.- dividende distribuite la PF', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 605, 13, N'605--Imp.pe ven.- dobanzi', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 609, 14, N'609--Imp.pe castigurile din transferul dr.de proprietate asupra titl.de val.', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 617, 15, N'617--Imp.pe castigurile din vanz.-cump.de valuta la termen', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 606, 16, N'606--Imp.pe ven.- lichidarerea unei PJ', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 608, 17, N'608--Imp.pe ven.- premii si din jocuri de noroc', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 613, 18, N'613--Impozitul pe veniturile din activitati agricole', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 690, 19, N'690--Imp.pe ven. din alte surse', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 612, 20, N'612--Imp.pe ven.obt.din Romania de nerezidenti - PF', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 140, 21, N'140--Imp.pe ven.obt.din Romania de nerezidenti - PJ', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 810, 22, N'810--Varsam.de la PJ pt.pers.cu handicap neincadrate', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 780, 23, N'780--Varsaminte din profitul net (regii autonome, societ.si companii nat.)', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 111, 24, N'111--Impozit pe profit scutit - art.38 (1) din Codul fiscal', N'BUGET DE STAT', 0, 0, 1, 0)
GO

INSERT INTO [Declaratii].[D100] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Rec], [Is_Cu_Ob], [Is_ImpM])
VALUES (N'20470101XX', 710, 25, N'710--Imp.la titeiul din prod.interna', N'BUGET DE STAT', 0, 0, 1, 0)
GO

IF Object_id('Declaratii.D101') IS NULL
	CREATE TABLE [Declaratii].[D101] (
	  [Indicator] varchar(240) COLLATE Latin1_General_CI_AS NULL,
	  [Nr] float NULL,
	  [Exp] text COLLATE Latin1_General_CI_AS NULL,
	  [Nr_Nou] float NULL
	)
	ON [PRIMARY]
	TEXTIMAGE_ON [PRIMARY]
GO

IF Object_id('Declaratii.D103') IS NULL
	CREATE TABLE [Declaratii].[D103] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Cod_Bug] char(10) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Nr_Evid3] numeric(3, 0) NOT NULL,
	  [Cod] numeric(3, 0) NOT NULL,
	  [Denumire] char(100) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Beneficiar] char(48) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Ok] numeric(1, 0) NOT NULL,
	  [Is_Ded] bit NOT NULL,
	  [Is_Rec] bit NOT NULL,
	  CONSTRAINT [D103_pk] PRIMARY KEY CLUSTERED ([Id])
	)
	ON [PRIMARY]
GO

ALTER TABLE [Declaratii].[D103] ALTER COLUMN [Ok] numeric(1, 0)
GO

Truncate TABLE [Declaratii].[D103]
GO

/* Data for the 'Declaratii.D103' table  (Records 1 - 29) */

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010205', 211, 1, N'211--Accize pt.bere', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010208', 216, 2, N'216--Accize pt.vinuri linistite', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010203', 212, 3, N'212--Accize pt.vinuri spumoase', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010207', 217, 4, N'217--Accize pt.bauturi ferment.linistite, altele decat bere si vinuri', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010204', 213, 5, N'213--Accize pt.bauturi ferment.spumoase, altele decat bere si vinuri', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010202', 214, 6, N'214--Accize pt.prod.intermediare', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010201', 215, 7, N'215--Accize pt.alcool etilic', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010301', 221, 8, N'221--Accize pt.tigarete', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010302', 222, 9, N'222--Accize pt.tigari si tigari de foi', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010303', 224, 10, N'224--Accize pt.tutun de fumat fin taiat, dest. rularii in tigarete', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010304', 225, 11, N'225--Accize pt.alte tutunuri de fumat', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010101', 231, 12, N'231--Accize pt.benzina cu plumb', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010102', 232, 13, N'232--Accize pt.benzina fara plumb si bietanol', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010103', 233, 14, N'233--Accize pt.motorina si biodiesel', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010104', 234, 15, N'234--Accize pt.pacura', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010105', 235, 16, N'235--Accize pt.gaz petrolier lichefiat', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010106', 236, 17, N'236--Accize pentru gaz natural', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010108', 238, 18, N'238--Accize pt.petrol lampant (kerosen)', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010107', 237, 19, N'237--Accize pentru carbune si cocs', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'20140106XX', 270, 20, N'270--Accize pt.en.electrica', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010401', 244, 21, N'244--Accize pt.cafea verde', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010402', 242, 22, N'242--Accize incasate din vanzarea de cafea prajita, inclusiv cafea cu inlocuitori', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010403', 243, 23, N'243--Accize incasate din vanzarea de cafea solubila', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010904', 261, 24, N'261--Accize pt.autoturisme', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2014010110', 275, 25, N'275--Accize pentru alte produse accizabile (energetice)', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2030010501', 755, 26, N'755--Redevente miniere', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'2030010502', 756, 27, N'756--Redevente petroliere', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'20030118XX', 620, 28, N'620--Imp.pe venitul din transferul proprietatii imobilizare din patrimoniul personal', N'BUGET DE STAT', 0, 1, 1)
GO

INSERT INTO [Declaratii].[D103] ([Cod_Bug], [Nr_Evid3], [Cod], [Denumire], [Beneficiar], [Ok], [Is_Ded], [Is_Rec])
VALUES (N'20160104XX', 750, 29, N'750--Taxa pe activ.de prospectiune explorare eploatare a resusrselor minerale', N'BUGET DE STAT', 0, 1, 1)
GO

IF Not Object_id('Declaratii.D300_DecontTva') Is Null
	DROP TABLE [Declaratii].[D300_DecontTva]
GO

IF Object_id('Declaratii.D300_DecontTva') IS NULL
	CREATE TABLE [Declaratii].[D300_DecontTva] (
	  [Cont] char(4) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Rand] char(6) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Denumire] char(250) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Is_Col1] bit NOT NULL,
	  [Is_Col2] bit NOT NULL,
	  [Cod1] char(5) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Cod2] char(5) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Cod3] char(5) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Cod4] char(5) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Cod5] char(5) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Jurnal] numeric(1, 0) NOT NULL
	)
	ON [PRIMARY]
GO

Truncate TABLE [Declaratii].[D300_DecontTva]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='D300_DecontTva' AND COLUMN_NAME='Rand1')
	ALTER TABLE [Declaratii].[D300_DecontTva] DROP COLUMN [Rand1]
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Cod1] char(5) COLLATE Latin1_General_CI_AS
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Cont] char(5) COLLATE Latin1_General_CI_AS
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Cod2] char(5) COLLATE Latin1_General_CI_AS
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Cod3] char(5) COLLATE Latin1_General_CI_AS
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Cod4] char(5) COLLATE Latin1_General_CI_AS
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Cod5] char(5) COLLATE Latin1_General_CI_AS
GO

ALTER TABLE [Declaratii].[D300_DecontTva] ALTER COLUMN [Jurnal] numeric(1, 0)
GO

/* Data for the 'Declaratii.D300_DecontTva' table  (Records 1 - 48) */

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4427', N'1', N'Livrari intracomunitare de bunuri, scutite cf.art.143 alin.(2) lit.a) si d) din Codul Fiscal', 1, 0, N'14', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'2', N'Regularizari livrari intracomunitare scutite conform art.143 alin.(2)  lit.a) si d) din Codul Fiscal', 1, 0, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'3', N'Livrari de bunuri sau prestari de servicii pentru care locul livrarii/ locul prestarii este in afara Romaniei (in UE sau in afara UE), precum si livrari intracomunitare de bunuri, scutite cf.art.143 alin.(2) lit.b) si c) din Codul Fiscal, din care:', 1, 0, N'12', N'13', NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'3.1', N'Prestari de servicii intracomunitare care nu beneficiaza de scutire in statul membru in care taxa este datorata', 1, 0, N'12', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'4', N'Regularizari privind prestarile de servicii intracomunitare care nu beneficieaza de scutire in statul membru in care este datorata', 1, 0, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'5', N'Achizitii intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa) din care:', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'5.1', N'Achizitii intracomunitare pentru care cumparatorul este obligat la plata TVA (taxare inversa), iar furnizorul este inregistrat in scopuri de TVA in statul membru din care a avut loc livrarea intracomunitara', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'6', N'Regularizari privind achizitii intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'7', N'ACHIZITII de bunuri, altele decat cele de la rd.4 si rd.5, si achizitii de servicii pentru care beneficiarul din Romania este obligat la plata TVA (taxare inversa), din care', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'7.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa) din care:', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'7.1.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa), iar prestatorul este inregistrat in scopuri de TVA in statul membru din care efectueaza prestarea de servicii', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'8', N'Regularizari privind achizitiile de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'9', N'LIVRARI de bunuri si prestari de servicii, taxabile cu cota 24%', 1, 1, N'6-7', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'10', N'LIVRARI de bunuri si prestari de servicii, taxabile cu cota  9%', 1, 1, N'8-9', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'11', N'LIVRARI de bunuri taxabile cu cota 5%', 1, 1, N'19-20', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'12', N'ACHIZITII de bunuri si servicii achizitionate supuse masurilor de simplificare pentru care beneficiarul este obligat la plata TVA (taxare inversa)', 1, 1, N'17-18', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'13', N'LIVRARI de bunuri si prestari de servicii scutite cu drept de deducere, cu exceptia celor de la rd.1-3, si operatiuni supuse masurilor de simplificare', 1, 0, N'15', N'16', NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'14', N'LIVRARI de bunuri si prestari de servicii scutite fara drept de deducere', 1, 0, N'17', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'15', N'Regularizari taxa colectata', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'16', N'TOTAL TAXA COLECTATA   (rd. 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4426', N'17', N'ACHIZITII intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa), din care:', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'17.1', N'Achizitii intracomunitare pentru care cumparatorul este obligat la plata TVA (taxare inversa), iar furnizorul este inregistrat in scopuri de TVA in statul membru din care a avut loc livrarea', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'18', N'Regularizari privind achizitii intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'19', N'ACHIZITII de bunuri , altele decat cele de la rd.17 si 18, si achizitii de servicii achizitionate pentru beneficiarul din Romania este obligat la plata TVA (taxare inversa), din care:', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'19.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa), din care:', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'19.1.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa), iar prestatorul este inregistrat in scopuri de TVA in statul memebru din care efectueaza prestarea de servicii', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'20', N'Regularizarile privind achizitiile de servicii intracomunitare pentru care beneficiarul din Romania este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'21', N'Achizitii de bunuri si servicii taxabile cu cota de 24%', 1, 1, N'6-7', N'17-18', NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'22', N'Achizitii de bunuri si servicii taxabile cu cota de  9%', 1, 1, N'8-9', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'23', N'Achizitii de bunuri taxabile cu cota de  5%', 1, 1, N'19-20', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'24', N'Achizitii de bunuri si servicii scutite de taxa sau neimpozabile, din care:', 1, 0, N'10', N'13', N'14', NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'24.1', N'Achizitii de servicii intracomunitare scutite de taxa', 1, 0, N'13', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'25', N'TOTAL TAXA DEDUCTIBILA (rd.17+18+19+20+21+22+23)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'26', N'SUB-TOTAL TAXA DEDUSA CONFORM ART.145  si 145^1 SAU 147 si 147^1', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'27', N'TVA efectiv restituita cumparatorilor straini, inclusiv comisionul unitatilor autorizate', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'28', N'Regularizari taxa dedusa', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'29', N'Ajustari la finele anului conform pro-rata/ ajustari pentru bunurile de capital', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'30', N'TOTAL TAXA DEDUSA (rd.26+27+28+29)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4424', N'31', N'Suma negativa a TVA in perioada de raportare (rd.30 - rd.16)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4423', N'32', N'Taxa de plata in perioada de raportare (rd.16 - rd.30)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4423', N'33', N'Soldul TVA de plata din decontul perioadei fiscale precedente (rd.39 din decontul perioadei fiscale precedente) neachitata pana la data depunerii decontului de TVA', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'34', N'Diferente de TVA de plata stabilite de organele de inspectie fiscala prin decizie comunicata si neachitate pana la data depunerii decontului de TVA', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'35', N'TVA de plata cumulat (rd.32+rd.33+rd.34)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4424', N'36', N'Soldul sumei negative a TVA reportata din perioada fiscala precedenta pentru care nu s-a solicitat rambursare (rd.40 din decontul perioadei fiscale precedente)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'37', N'Diferente negative de TVA stabilite de organele de inspectie fiscala prin decizie comunicata pana la data depunerii decontului de TVA', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'38', N'Suma negativa a TVA cumulate (rd.31+rd.36+rd.37)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4423', N'39', N'Sold TVA de plata la sfarsitul perioadei de raportare (rd.35-rd.38)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4424', N'40', N'Soldul sumei negative de TVA la sfarsitul perioadei de raportare (rd.38-rd.35)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

Update Declaratii.D300_DecontTva Set Is_Col1 = 0 Where IsNull(Is_Col1, 0) = 0
Update Declaratii.D300_DecontTva Set Is_Col2 = 0 Where IsNull(Is_Col2, 0) = 0
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Special')
	EXEC sp_rename 'dbo.Special', 'OperatiiSpeciale'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='OperatiiSpeciale' AND COLUMN_NAME='IdUnic')
	ALTER TABLE dbo.OperatiiSpeciale ADD [IdUnic] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='OperatiiSpeciale' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE dbo.OperatiiSpeciale ADD [iUserWorking] int NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='OperatiiSpeciale' AND COLUMN_NAME='Data')
	EXEC sp_rename '[dbo].[OperatiiSpeciale].[Data]', 'DataDoc', 'COLUMN'
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='OperatiiSpeciale' AND COLUMN_NAME='DataDoc')
	ALTER TABLE [dbo].[OperatiiSpeciale] ALTER COLUMN [DataDoc] date NOT NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='OperatiiSpeciale' AND COLUMN_NAME='Nr')
	EXEC sp_rename '[dbo].[OperatiiSpeciale].[Nr]', 'NumarDoc', 'COLUMN'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='PreturiAmanunt' AND COLUMN_NAME='IdUnic')
	ALTER TABLE dbo.PreturiAmanunt ADD [IdUnic] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE Configurari.ConfigurareConturi ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Id')
	ALTER TABLE Configurari.ConfigurareConturi ADD [Id] int DEFAULT 1 NOT NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='CheltSpon')
	ALTER TABLE Configurari.ConfigurareConturi ADD [CheltSpon] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fur')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Fur] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='FurImob')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [FurImob] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Cli')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Cli] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Casa')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Casa] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Banca')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Banca] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Banca2')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Banca2] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Banca3')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Banca3] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Dec')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Dec] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Dec2')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Dec2] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Dec3')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Dec3] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='CasaV')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [CasaV] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='BancaV')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [BancaV] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='BancaV2')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [BancaV2] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='BancaV3')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [BancaV3] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='DecV')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [DecV] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='DecV2')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [DecV2] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='DecV3')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [DecV3] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaPl')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaPl] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaRe')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaRe] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaNe')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaNe] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaDe')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaDe] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaCo')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaCo] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Marfuri')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [Marfuri] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='c121')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [c121] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='c121_sec')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [c121_sec] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='c6')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [c6] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='c7')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [c7] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='oi_fol')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [oi_fol] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='c403')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [c403] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='c413')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [c413] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='impp')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [impp] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='impv')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [impv] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='cheltimpp')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [cheltimpp] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='cheltimpv')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [cheltimpv] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='cheltprot')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [cheltprot] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='cAvizeClienti')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [cAvizeClienti] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='cAvizeFurnizori')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [cAvizeFurnizori] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaVama')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaVama] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='TvaPlataVama')
	ALTER TABLE Configurari.ConfigurareConturi ALTER COLUMN [TvaPlataVama] char(20) COLLATE Latin1_General_CI_AS NULL
GO

IF Object_id('Configurari.ConfigurareConturi') IS NULL
	CREATE TABLE [Configurari].[ConfigurareConturi] (
	  [Fur] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [FurImob] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Cli] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Casa] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Banca] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Banca2] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Banca3] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Dec] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Dec2] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Dec3] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [CasaV] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [BancaV] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [BancaV2] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [BancaV3] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [DecV] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [DecV2] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [DecV3] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [TvaPl] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [TvaRe] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [TvaNe] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [TvaDe] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [TvaCo] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Marfuri] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [c121] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [c121_sec] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [c6] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [c7] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Oi_Fol] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [c403] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [c413] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [ImpP] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [ImpV] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [CheltImpP] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [CheltImpV] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [CheltProt] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [cAvizeClienti] char(20) COLLATE Latin1_General_CI_AS DEFAULT 418 NULL,
	  [cAvizeFurnizori] char(20) COLLATE Latin1_General_CI_AS DEFAULT 408 NULL,
	  [TvaVama] char(20) COLLATE Latin1_General_CI_AS DEFAULT 446 NULL,
	  [TvaPlataVama] char(20) COLLATE Latin1_General_CI_AS DEFAULT 5121 NULL,
	  [iUserWorking] int NULL,
	  [Id] int DEFAULT 1 NOT NULL,
	  [CheltSpon] char(20) COLLATE Latin1_General_CI_AS NULL,
	  CONSTRAINT [ConfigurareConturi_pk] PRIMARY KEY CLUSTERED ([Id])
	)
	ON [PRIMARY]
GO

IF Object_id('dbo.Import_Date') IS NULL
	CREATE TABLE [dbo].[Import_Date] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Denumire] varchar(60) COLLATE Latin1_General_CI_AS NULL,
	  [Fisier] varchar(100) COLLATE Latin1_General_CI_AS NULL,
	  [Data] date NULL,
	  [Transferat] bit DEFAULT 0 NULL,
	  [Tip] int NULL,
	  PRIMARY KEY CLUSTERED ([Id])
	)
	ON [PRIMARY]
GO

IF Object_id('dbo.InchideriCheltuieliVenituri') IS NULL
	CREATE TABLE [dbo].[InchideriCheltuieliVenituri] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Luna] numeric(2, 0) NOT NULL,
	  [An] numeric(4, 0) NOT NULL,
	  [Cont] char(20) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Denumire] char(48) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Suma] numeric(14, 2) NOT NULL,
	  [NeDed] numeric(14, 2) NULL,
	  [Impozitat] numeric(14, 2) NULL,
	  PRIMARY KEY CLUSTERED ([Id])
	)
	ON [PRIMARY]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='InchideriCheltuieliVenituri' AND COLUMN_NAME='Neded')
	ALTER TABLE [dbo].[InchideriCheltuieliVenituri] ALTER COLUMN [Neded] numeric(14, 2)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='InchideriCheltuieliVenituri' AND COLUMN_NAME='Impozitat')
	ALTER TABLE [dbo].[InchideriCheltuieliVenituri] ALTER COLUMN [Impozitat] numeric(14, 2)
GO

If Exists ( Select * From sys.triggers Where Name = 'conturi_tri' )
	Drop Trigger [dbo].[conturi_tri]
GO

CREATE TRIGGER [dbo].[conturi_tri] ON [dbo].[conturi]
WITH EXECUTE AS CALLER
FOR INSERT
AS
Begin
	Declare @Count int;
	Set @Count = @@ROWCOUNT;
	If @Count = 0 
		Return;
	Set NoCount On;
	Begin Try
		Declare @ContInserat VarChar(20)
		Declare @TipContInserat VarChar(1)
        Declare @nLenCont Int
		--DECLARE @Clienti varchar(20)
		--EXEC  spGetSystemParameter 'iCustomer',@Clienti OUTPUT
		Set @ContInserat = (Select Cont From Inserted)
		Set @TipContInserat = (Select tip From Inserted)
        Set @nLenCont = 3
		/*
        SET @nLenCont = 
 			CASE 
            	WHEN LEFT(@ContInserat, 3) = '411' THEN LEN(@Clienti)
				ELSE 3
        	END 
        */    
            If Not Exists (Select Cont From Conturi Where Cont=Left(@ContInserat, @nLenCont))
            	Begin
	            	Insert Into Conturi (Cont, Denumire, Tip) 
    	        	Values (Left(@ContInserat,@nLenCont), '', @TipContInserat) 
                End
	End Try
    Begin Catch
        Execute [dbo].[uspPrintError];
        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        If @@TranCount > 0
        Begin
            RollBack Transaction;
        End
        Execute [dbo].[uspLogError];
    End Catch;
End
GO

If Exists ( Select * From sys.triggers Where Name = 'Iesiri_tru')
	DROP TRIGGER [dbo].[Iesiri_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Import_tru')
	DROP TRIGGER [dbo].[Import_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Intrari_tru')
	DROP TRIGGER [dbo].[Intrari_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'inventar_tru')
	DROP TRIGGER [dbo].[inventar_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'NotePredare_tru')
	DROP TRIGGER [dbo].[NotePredare_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'NotePredareDetaliat_tru')
	DROP TRIGGER [dbo].[NotePredareDetaliat_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Iesiri_tru' )
	Drop Trigger [dbo].[Iesiri_tru]
GO

CREATE TRIGGER [dbo].[Iesiri_tru] ON [dbo].[Iesiri]
WITH EXECUTE AS CALLER
FOR UPDATE
AS
Begin
	Declare @Count int;
	Set @Count = @@ROWCOUNT;
	If @Count = 0 
		Return;
		Set NoCount On;
	Begin Try
		/*** Sincronizare CT cu Anulat Din Iesiri ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where IsNull(d.Anulat, 0)<>IsNull(i.Anulat, 0) And IsNull(i.Anulat, 0) = 1)
		Update c Set 
        	IdFactura = Null,
            NumarFactura = Null,
            DataFactura = Null,
            DataScadenta = Null,
            ValoareFactura = Null,
            Neachitat = Null
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT Cont si Denumire ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where d.Cont<>i.Cont)
		Update c Set Cont = i.Cont, Beneficiar = i.DenumireClient
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT NumarFactura ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where d.NumarDoc<>i.NumarDoc)
		Update c Set NumarFactura = i.NumarDoc
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT TotalValuta ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where d.Total<>i.Total)
		Update c Set ValoareFactura = i.Total
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT DataDoc ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On Ct.IdFactura = i.IdUnic Where d.DataDoc<>i.DataDoc)
		Update c Set DataFactura = i.DataDoc
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT Scadenta ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On Ct.IdFactura = i.IdUnic Where d.Scadenta<>i.Scadenta)
		Update c Set DataScadenta = i.Scadenta
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
	End Try
	Begin Catch
		Execute [dbo].[uspPrintError];
		-- Rollback any active or uncommittable transactions before
		-- inserting information in the ErrorLog
		If @@TranCount > 0
			Begin
				RollBack Transaction;
			End
			Execute [dbo].[uspLogError];
	End Catch;
End;
GO

If Exists ( Select * From sys.triggers Where Name = 'Export_tru' )
	Drop Trigger [dbo].[Export_tru]
GO

CREATE TRIGGER [dbo].[Export_tru] ON [dbo].[Export]
WITH EXECUTE AS CALLER
FOR UPDATE
AS
Begin
	Declare @Count int;
	Set @Count = @@ROWCOUNT;
	If @Count = 0 
		Return;
		Set NoCount On;
	Begin Try
		/*** Sincronizare CT cu Anulat Din Export ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where IsNull(d.Anulat, 0)<>IsNull(i.Anulat, 0) And IsNull(i.Anulat, 0) = 1)
		Update c Set 
        	IdFactura = Null,
            NumarFactura = Null,
            DataFactura = Null,
            DataScadenta = Null,
            ValoareFactura = Null,
            Neachitat = Null,
            Curs = Null
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT Cont si Denumire ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where d.Cont<>i.Cont)
		Update c Set Cont = i.Cont, Beneficiar = i.DenumireClient
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT NumarFactura ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where d.NumarDoc<>i.NumarDoc)
		Update c Set NumarFactura = i.NumarDoc
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT TotalValuta ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On ct.IdFactura = i.IdUnic Where d.TotalValuta<>i.TotalValuta)
		Update c Set ValoareFactura = i.TotalValuta
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT DataDoc ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On Ct.IdFactura = i.IdUnic Where d.DataDoc<>i.DataDoc)
		Update c Set DataFactura = i.DataDoc
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT Scadenta ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On Ct.IdFactura = i.IdUnic Where d.Scadenta<>i.Scadenta)
		Update c Set DataScadenta = i.Scadenta
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT CodValuta ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On Ct.IdFactura = i.IdUnic Where d.CodValuta<>i.CodValuta)
		Update c Set CodValuta = i.CodValuta
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
		/*** Sincronizare CT Curs ***/
		If Exists(
        	Select 1 
            From deleted d 
            Inner Join Inserted i On d.IdDoc = i.IdDoc 
	       	Inner Join ComenziTransport.Comenzi ct On Ct.IdFactura = i.IdUnic Where d.Curs<>i.Curs)
		Update c Set Curs = i.Curs
        From ComenziTransport.Comenzi c
        Inner Join Inserted i On c.IdFactura = i.IdUnic
	End Try
	Begin Catch
		Execute [dbo].[uspPrintError];
		-- Rollback any active or uncommittable transactions before
		-- inserting information in the ErrorLog
		If @@TranCount > 0
			Begin
				RollBack Transaction;
			End
			Execute [dbo].[uspLogError];
	End Catch;
End;
GO

If Exists ( Select * From sys.triggers Where Name = 'Categorii_trd' )
	Drop Trigger [dbo].[Categorii_trd]
GO

CREATE TRIGGER [dbo].[Categorii_trd] ON [dbo].[Categorii]
	WITH EXECUTE AS CALLER
	FOR DELETE
	AS
	BEGIN
	  /* Sa nu fie folosit in IntrariDetaliat  */
	 DECLARE @DenCateg varchar(50) = (SELECT LTRIM(Denumire) FROM Deleted) 
	 DECLARE @msg varchar(150) 
	IF  Exists(Select * FROM Deleted WHERE Id IN 
		(SELECT IdCategorie From IntrariDetaliat))
	 BEGIN
	 set @msg = 'Aveti  date in Facturi de Intrare pe acest Centru de Cost!'+char(13) +space(25)+ @DenCateg 
		RAISERROR(@msg,16,1)
		ROLLBACK TRANSACTION
		RETURN
	 END
	  
	  /* Sa nu fie folosit in IesiriDetaliat  */
	IF  Exists(Select * FROM Deleted WHERE Id IN 
		(SELECT IdCategorie From IesiriDetaliat ))
	 BEGIN
	 set @msg = 'Aveti  date in  Facturi de Iesire pe acest Centru de Cost!'+char(13) +space(25)+ @DenCateg 
		RAISERROR(@msg,16,1)
		ROLLBACK TRANSACTION
		RETURN
	 END

	  /* Sa nu fie folosit in BCDetaliat  */
	IF  Exists(Select * FROM deleted WHERE Id IN 
		(SELECT IdCategorie From BonuriConsum ))
	 BEGIN
	 set @msg = 'Aveti date in Bonuri de Consum pe acest Centru de Cost!'+char(13) +space(25)+ @DenCateg 
		RAISERROR(@msg,16,1)
		ROLLBACK TRANSACTION
		RETURN
	 END

	  /* Sa nu fie folosit in NotePredareDetaliat  */
	IF  Exists(Select * FROM deleted WHERE Id IN 
		(SELECT IdCategorie From NotePredareDetaliat ))
	 BEGIN
	 set @msg = 'Aveti date in  Note Predare pe acest Centru de Cost!'+char(13) +space(25)+ @DenCateg 
		RAISERROR(@msg,16,1)
		ROLLBACK TRANSACTION
		RETURN
	 END

	  /* Sa nu fie folosit in Articole  */
	IF  Exists(Select * FROM Deleted WHERE Id IN 
		(SELECT IdCategorie From Articole))
	 BEGIN
	 set @msg = 'Aveti date in  Articole pe aceasta Categorie de Articole!'+char(13) +space(25)+ @DenCateg 
		RAISERROR(@msg,16,1)

	RAISERROR(@msg,16,0)
		ROLLBACK TRANSACTION
		RETURN
	 END

	  /* Sa nu fie folosit in Imobilizari  */
	IF  Exists(Select * FROM Deleted WHERE Id IN 
		(SELECT IDCategorie From MijloaceFixe))
	 BEGIN
	 set @msg = 'Aveti date in Imobilizari pe acest Centru de Cost!'+char(13) +space(25)+ @DenCateg 
		RAISERROR(@msg,16,1)
		ROLLBACK TRANSACTION
		RETURN
	 END

	END
GO

If Exists ( Select * From sys.triggers Where Name = 'conturi_tru' )
	Drop Trigger [dbo].[conturi_tru]
GO

CREATE TRIGGER [dbo].[conturi_tru] ON [dbo].[conturi]
WITH EXECUTE AS CALLER
FOR UPDATE
NOT FOR REPLICATION
AS
BEGIN

    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
	DECLARE @UpdateId int =	(SELECT Id FROM Deleted);
	DECLARE @Cont Char(20) = (SELECT Cont FROM Deleted); 
   	DECLARE @ContTRIM nVarChar(20) = (SELECT LEFT(Cont,LEN(Cont)) FROM Deleted); 

    --IF UPDATE([Sters])	
    IF Exists( SELECT * FROM Deleted d INNER JOIN Inserted i ON d.Id = i.Id WHERE d.Sters <> i.Sters)
    AND Exists(
			Select Id FROM Deleted 
				WHERE 
                	Cont IN (SELECT ContD From Registru)
                	OR Cont IN (SELECT ContC From Registru)
                )
        BEGIN
			ROLLBACK TRANSACTION
            RAISERROR ('Nu pot STERGE Contul %s deoarece a fost folosit in Note Contabile!', 16, 1,@ContTRIM)
            RETURN
        END
	
	IF Exists( SELECT * FROM Deleted d INNER JOIN Inserted i ON d.Id = i.Id WHERE IsNull(d.Sters, 0) <> IsNull(i.Sters, 0))
			AND Exists( 
            	Select Id FROM Deleted 
                	WHERE Cont IN ( SELECT Cont FROM ComenziTransport.Comenzi) 
                )
        BEGIN
			ROLLBACK TRANSACTION
            RAISERROR ('Nu pot STERGE Contul %s deoarece a fost folosit in ComenziTransport!', 16, 1,@ContTRIM)
            RETURN
        END
  
	--IF UPDATE([Cont])
   IF Exists( SELECT * FROM Deleted d INNER JOIN Inserted i ON d.Id = i.Id WHERE d.Cont <> i.Cont)
		AND Exists(
			Select Cont FROM Deleted 
				WHERE 
                	Cont IN (SELECT ContD From Registru)
                	OR Cont IN (SELECT ContC From Registru)
                )
        BEGIN
			ROLLBACK TRANSACTION
            RAISERROR ('Nu pot MODIFICA Contul %s deoarece a fost folosit in Note Contabile!', 16, 1,@ContTRIM)
            RETURN
        END
	IF Exists( SELECT * FROM Deleted d INNER JOIN Inserted i ON d.Id = i.Id WHERE d.Cont <> i.Cont)
		AND Exists( 
        	Select Cont FROM Deleted 
            	WHERE Cont IN ( SELECT Cont FROM ComenziTransport.Comenzi) 
                )
        BEGIN


			ROLLBACK TRANSACTION
            RAISERROR ('Nu pot MODIFICA Contul %s deoarece a fost folosit in ComenziTransport!', 16, 1,@ContTRIM)
            RETURN
        END
	-- Daca a modificat Denumirea Contului
	IF Exists( SELECT * FROM Deleted d INNER JOIN Inserted i ON d.Id = i.Id WHERE d.Denumire <> i.Denumire)
		AND Exists( 
        	Select Cont FROM Deleted 
            	WHERE Cont IN ( SELECT Cont FROM ComenziTransport.Comenzi) 
                )
	--IF UPDATE(Denumire)
	Begin 
		Update ComenziTransport.Comenzi SET Beneficiar=Inserted.Denumire 
        FROM ComenziTransport.Comenzi 
        	INNER JOIN Inserted
            	ON ComenziTransport.Comenzi.Cont=Inserted.Cont
	End	

    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];
        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END
        EXECUTE [dbo].[uspLogError];
    END CATCH;
END
GO

If Object_Id('IsAlpha') Is Not Null
  Drop Function [IsAlpha]
GO

Create Function IsAlpha (@String VarChar(max))
Returns Int
As 
Begin
	Set @String = SubString(@String, 1, 1)
	Return
		Case
			When PatIndex('%[^a-zA-Z]%', @String) > 0 Then 0
			Else 1
		End
End
GO

If Object_Id('IsDigit') Is Not Null
  Drop Function [IsDigit]
GO

Create Function IsDigit (@String VarChar(Max))  
/*
Select dbo.IsDigit('how many times must I tell you')
Select dbo.IsDigit('294856')
Select dbo.IsDigit('569.45')
*/
Returns Int
As
Begin
	Return
		Case 
			When PatIndex('%[^0-9]%', @String) > 0 Then 0
			Else 1
		End
End
GO

If Object_Id('GetNextInvoiceNumber') Is Not Null
  Drop Function [GetNextInvoiceNumber]
GO

Create Function GetNextInvoiceNumber(@cActualNumber VarChar(20))
Returns Char(20)
As
Begin
	Declare @cNextFactura Char(20)
	-- Set @pActualNumber = Replace(@pActualNumber , ' ', '')  
    Declare @cIntermed Char(20) = RTrim(LTrim(@cActualNumber))
    Declare @nLenNr Numeric(20) = Len(@cIntermed)
	Declare @nNrMax Numeric(20) = 0
    Declare @nLoop int 			= 1
	-- Aflu Prefix
	While @nLoop <= @nLenNr
    Begin
		If dbo.IsAlpha(SubString(@cActualNumber, @nLoop, 1)) = 1
        	Or SubString(@cActualNumber, @nLoop, 1) In (' ', '-', '/', '_')
        Begin
        	Set @nNrMax = @nNrMax + 1
        End
        Else
        	Break
    	Set @nLoop = @nLoop + 1
    End
	Declare @cPrefix Char(20) = Left(RTrim(LTrim(@cActualNumber)), @nNrMax)
	Set @cIntermed = Right(RTrim(LTrim(@cIntermed)), @nLenNr - @nNrMax)
	-- Aflu Numar
	Declare @nNrMaxNumber Numeric(20) = 0
	Declare @cNumar Char(20) = ''
	Declare @cNextNumber Char(20) = ''
    Declare @nLenNrIntermediar Numeric(20) = Len(RTrim(LTrim(@cIntermed)))
    Set @nLoop= 1
    While @nLoop <= @nLenNrIntermediar
    Begin
	    If dbo.IsDigit(SubString(RTrim(LTrim(@cIntermed)), @nLoop, 1)) = 1
        Begin
			Set @cNumar = RTrim(LTrim(@cNumar)) + SubString(RTrim(LTrim(@cIntermed)), @nLoop, 1)
			Set @nNrMaxNumber = @nNrMaxNumber + 1
		End
        Else
       		Break
		Set @nLoop = @nLoop + 1    
	End
    -- Return @cNumar
    Set @cNextNumber = RTrim(LTrim( Cast(Cast(RTrim(LTrim(@cNumar)) As Numeric(20))+1 As Char(20))))
    Set @cNextNumber = RTrim( LTrim( @cNextNumber) )
	-- Aflu Prefix	
	Declare @cSufix Char(20) = ''	
	Set @cSufix  = Right(RTrim(LTrim(@cIntermed)), @nLenNr- @nNrMax - @nNrMaxNumber)
    Set @cSufix  = RTrim( LTrim( @cSufix ))
	-- Aflu urmatorul Numar De Factura
	Set @cNextFactura =RTrim(LTrim(@cPrefix)) + RTrim(LTrim(@cNextNumber)) + RTrim(LTrim(@cSufix))
	Return @cNextFactura
End
GO

If Object_Id('GetNumberFromString') Is Not Null
  Drop Function [GetNumberFromString]
GO

Create Function GetNumberFromString (@String VarChar(Max))
Returns Numeric(20)
As
Begin
	-- Set @String = Replace (@String , ' ', '')  
    Declare @cNumericString VarChar(20) = ''
    Declare @nLoop Int = 1
    Declare @nLenString Numeric(20) = Len( RTrim ( LTrim( @String ) ) )
    While @nLoop <= @nLenString
    Begin
		If dbo.IsDigit(SubString(RTrim ( LTrim( @String ) ), @nLoop, 1)) = 1 
		Begin
        	Set @cNumericString  = @cNumericString + RTrim( LTrim ( SubString(RTrim ( LTrim( @String ) ), @nLoop, 1) ) )
        End
        Set @nLoop = @nLoop + 1 
	End
	Return Cast(@cNumericString As Numeric(20))
End
GO

If Object_Id('Max2') Is Not Null
  Drop Function [Max2]
GO

Create Function dbo.Max2
       (
            @Value1 Decimal(12, 4) = 0,
            @Value2 Decimal(12, 4) = 0
       )
Returns Decimal(12, 4)
As
Begin
	Declare @Result Decimal(12, 4)
    Set @Value1 =IsNull(@Value1, 0)
    Set @Value2 =IsNull(@Value2, 0)
    If @Value1 >= @Value2
        Set @Result = @Value1
    Else
       Set @Result = @Value2
    Return @Result
End
GO

If Object_Id('udf_RotunjireInSus') Is Not Null
  Drop Function [udf_RotunjireInSus]
GO

CREATE Function udf_RotunjireInSus (@Numar numeric(22,6),@Zecimale int)  
Returns Numeric(22,6)
As  
Begin
	Return Ceiling(@Numar*Power(10, @Zecimale)) / Power(10, @Zecimale)
End
GO

If Object_Id('udf_cifra_litera') Is Not Null
  Drop Function [udf_cifra_litera]
GO

Create Function udf_cifra_litera (@Cifra int, @Poz int)
Returns nVarChar(10)
As
Begin
	Declare @Rez nVarChar(10)
	Set @Rez =
          Case
              When @Cifra = 0 Then ''
              When @Cifra = 1 Then 'unu'
              When @Cifra = 2 And @Poz = 1 Then 'doua'
              When @Cifra = 2 And @Poz <> 1 Then 'doua'
              When @Cifra = 3 Then 'trei'
              When @Cifra = 4 Then 'patru'
              When @Cifra = 5 Then 'cinci'
              When @Cifra = 6 And @Poz = 1 Then 'sase'
              When @Cifra = 6 And @Poz <> 1 Then 'sai'
              When @Cifra = 7 Then 'sapte'
              When @Cifra = 8 Then 'opt'
              When @Cifra = 9 Then 'noua'
          End
	Return @Rez
End
GO


If Object_Id('udf_grup_2cifre') Is Not Null
  Drop Function [udf_grup_2cifre]
GO

CREATE Function dbo.udf_grup_2cifre (@Grup int)
Returns nVarChar(100)
As
Begin
	Declare @rez nvarchar(100)
	Declare @ngrup nvarchar(3)
	Set @ngrup = Convert(nvarchar(3),@grup)
	Set @rez =
	Case
		When Len(@ngrup) = 1 then dbo.udf_cifra_litera (@grup,1)
		When Len(@ngrup) = 2 And Convert(int,(@grup/10)) <> 1 and @grup - Convert(int,(@grup/10))*10 = 0 Then dbo.udf_cifra_litera (convert(int,(@grup/10)),2) + 'zeci'
		When Len(@ngrup) = 2 And Convert(int,(@grup/10)) <> 1 and @grup - Convert(int,(@grup/10))*10 <> 0 Then dbo.udf_cifra_litera (convert(int,(@grup/10)),2) + 'zecisi' + dbo.udf_cifra_litera (@grup - convert(int,(@grup/10))*10,1)
		When Len(@ngrup) = 2 And Convert(int,(@grup/10)) = 1 and @grup - Convert(int,(@grup/10))*10 <> 0 Then dbo.udf_cifra_litera (@grup - convert(int,(@grup/10))*10,1) + 'sprezece'
		When Len(@ngrup) = 2 And Convert(int,(@grup/10)) = 1 and @grup - Convert(int,(@grup/10))*10 = 0 Then 'zece'
	End
	Return @rez
End
GO

If Object_Id('udf_grup_3cifre') Is Not Null
  Drop Function [udf_grup_3cifre]
GO

CREATE Function dbo.udf_grup_3cifre(@grup int)
Returns nvarchar(100)
As
Begin
	Declare @rez nvarchar(100)
	Declare @ngrup nvarchar(3)
	Set @ngrup = convert(nvarchar(3),@grup)
	Set @rez =
	Case
		When @grup < 100 Then dbo.udf_grup_2cifre (@grup)
		When @grup = 100 Then 'unasuta'
		When @grup > 100 And @grup < 200 Then 'unasuta' + dbo.udf_grup_2cifre (@grup - 100)
		When @grup >= 200 Then dbo.udf_cifra_litera (Convert(int,@grup/100),1) + 'sute' + dbo.udf_grup_2cifre (@grup - Convert(int,@grup/100)*100)
	End
	Return @rez
End
GO

If Object_Id('udf_numar_litere') Is Not Null
  Drop Function [udf_numar_litere]
GO

CREATE Function dbo.udf_numar_litere  (@grup int)
Returns nVarChar (100)
As
Begin
	Declare @rez nVarChar (100)
	Declare @ngrup nVarChar (20)
	SET @ngrup = CONVERT (nVarChar (20), @grup)
	SET @rez =
	Case
		WHEN @grup < 1000
			THEN dbo.udf_grup_3cifre (@grup)
		WHEN @grup >= 1000 AND @grup < 1000000
			THEN dbo.udf_grup_3cifre (CONVERT (int, @grup / 1000)) + 'mii'
			+ dbo.udf_grup_3cifre (@grup - CONVERT (int, @grup / 1000) * 1000)
		WHEN @grup >= 1000000 AND @grup < 1000000000
			THEN dbo.udf_grup_3cifre (CONVERT (int, @grup / 1000000)) + 'milioane'
			+ dbo.udf_grup_3cifre (CONVERT (int, (@grup - CONVERT (int, @grup / 1000000) * 1000000) / 1000))
			+ CASE
				WHEN len (dbo.udf_grup_3cifre (CONVERT (int, (@grup - CONVERT (int, @grup / 1000000) * 1000000) / 1000))) <> 0
				THEN 'mii'
				ELSE ''
			END
			+ dbo.udf_grup_3cifre ((@grup - CONVERT (int, @grup / 1000000) * 1000000) - CONVERT (int, (@grup - CONVERT (int, @grup / 1000000) * 1000000) / 1000) * 1000)
	End
	Return @rez
End
GO

If Object_Id('CharIndex_BIN') Is Not Null
  Drop Function [CharIndex_BIN]
GO

Create Function CharIndex_BIN(@Expression1 nVarChar(4000), @Expression2  nVarChar(4000), @Start_Location SmallInt = 1)
Returns nVarChar(4000)
As
 	/******************************************************************************************************************************
	
	Similar to the Transact-SQL Function CharIndex, but regardless of collation Settings, executes Case-sensitive search  
	
	******************************************************************************************************************************/	
    Begin
		Return CharIndex( @Expression1 Collate Latin1_General_BIN, @Expression2 Collate Latin1_General_BIN, @Start_Location)
    End
GO

If Object_Id('CharIndex_CI') Is Not Null
  Drop Function [CharIndex_CI]
GO

Create Function CharIndex_CI(@Expression1 nVarChar(4000), @Expression2  nVarChar(4000), @Start_Location  SmallInt = 1)
Returns nVarChar(4000)
As
 	/******************************************************************************************************************************
	
	Similar to the Transact-SQL Function CharIndex, but regardless of collation Settings,  executes Case-insensitive search  
	
	******************************************************************************************************************************/	
    Begin
		Return CharIndex( @Expression1 Collate Latin1_General_CI_As , @Expression2   Collate Latin1_General_CI_As , @Start_Location )
    End
GO

If Object_id('Occurs') Is Not Null
  Drop Function [Occurs]
GO

 
Create Function Occurs  (@cSearchExpression nVarChar(4000), @cExpressionSearched nVarChar(4000))
Returns SmallInt
As
 	/******************************************************************************************************************************
	
	Occurs() User-Defined Function
		Occurs(@cSearchExpression, @cExpressionSearched) Return Values SmallInt 
		Returns the number of times a Character expression Occurs within another Character expression (including  overlaps).
		
		Occurs is slowly than Occurs2.

	PARAMETERS
		@cSearchExpression nVarChar(4000) specifies a Character expression that Occurs() searches for within @cExpressionSearched. 
		@cExpressionSearched nVarChar(4000) specifies the Character expression Occurs() searches for @cSearchExpression. 
	
	REMARKS
		Occurs() Returns 0 (zero) If @cSearchExpression is not found within @cExpressionSearched.
	
	EXAMPLE
		Declare @gcString nVarChar(4000)
		Select  @gcString = 'abracadabra'
		Select dbo.Occurs('a', @gcString )  -- Displays 5
		Select dbo.Occurs('b', @gcString )  -- Displays 2
		Select dbo.Occurs('c', @gcString )  -- Displays 1
		Select dbo.Occurs('e', @gcString )  -- Displays 0
		Including  overlaps !!!
		Select dbo.Occurs('ABCA', 'ABCABCABCA') -- Displays 3
		1 occurrence of SubString 'ABCA  .. BCABCA' 
		2 occurrence of SubString 'ABC...ABCA...BCA' 
		3 occurrence of SubString 'ABCABC...ABCA' 
	
	See Also AT(), RAT(), Occurs2(), AT2(), ATC(), ATC2()    
	
	UDF the name And Functionality of which correspond to the  Visual FoxPro Function  
		(but Function Occurs of Visual FoxPro counts the 'Occurs' excluding  overlaps !)
	******************************************************************************************************************************/		 
	Begin
		Declare 
			@start_location SmallInt,  
			@Occurs  SmallInt
		Select  @start_location = -1,   @Occurs = -1
		While @start_location <> 0
			Select  
				@Occurs = @Occurs + 1,  
				@start_location  = CharIndex(@cSearchExpression Collate Latin1_General_BIN, @cExpressionSearched Collate Latin1_General_BIN, @start_location+1)
	Return @Occurs
	End
GO

If Object_id('Occurs2') Is Not Null
  Drop Function [Occurs2]
GO

Create Function Occurs2(@cSearchExpression nVarChar(4000), @cExpressionSearched nVarChar(4000))
Returns SmallInt
As
 	/******************************************************************************************************************************

	Occurs2() User-Defined Function
		Occurs2(@cSearchExpression, @cExpressionSearched) 
		Return Values SmallInt
		Returns the number of times a Character expression Occurs  within another Character expression (excluding  overlaps).
		
		Occurs2 is Faster than Occurs!.

	PARAMETERS
		@cSearchExpression nVarChar(4000) specifies a Character expression that Occurs2() searches for within @cExpressionSearched. 
		@cExpressionSearched nVarChar(4000) specifies the Character expression Occurs2() searches for @cSearchExpression. 
	
	REMARKS
		Occurs2() Returns 0 (zero) If @cSearchExpression is not found within @cExpressionSearched.

	EXAMPLE
		Declare @gcString nVarChar(4000)
		Select  @gcString = 'abracadabra'
		Select dbo.Occurs2('a', @gcString )  -- Displays 5

	Attention !!!
		This Function counts the 'Occurs' excluding  overlaps !
		Select dbo.Occurs2('ABCA', 'ABCABCABCA') -- Displays 2
		1 occurrence of SubString 'ABCA  .. BCABCA' 
		2 occurrence of SubString 'ABCABC... ABCA' 

	UDF the Functionality of which correspond to the  Visual FoxPro Function 

	See Also Occurs()  

	******************************************************************************************************************************/		 	 
	Begin
		Return
			Case  
				When DataLength(@cSearchExpression) > 0
					Then   
						( DataLength(@cExpressionSearched) 
						- DataLength(Replace(
											@cExpressionSearched Collate Latin1_General_BIN, 
											@cSearchExpression Collate Latin1_General_BIN, ''
											)
									)
						)  
						/ DataLength(@cSearchExpression)
				Else 0 
			End
	End
GO

IF Object_id('GetTipTert') IS NOT NULL
  DROP FUNCTION [GetTipTert]
GO

Create Function dbo.GetTipTert (@Cont Char(20))
Returns Char(1)
As
Begin
	Return
	(
    	Select IsNull(Tip_Tert, '1') 
        From Conturi 
        	Where 
            	Cont = @Cont 
            	And IsNull(Sters, 0) = 0 
	)           
End
GO

IF Object_id('GetListColumns') IS NOT NULL
  DROP FUNCTION [GetListColumns]
GO

-- GetListColumn -- returneaza lista campurilor dintr-o tabela cu virgula
Create Function GetListColumns (@Table VarChar(254), @Schema VarChar(254))
	RETURNS VarChar(1000)
	AS BEGIN
		IF @Schema IS NULL SET @Schema='dbo'
			
		DECLARE @k varchar(1000)
		SELECT @k = 
			(
			SELECT TOP 1 
				STUFF
					(
						(SELECT ', ' + T2.Column_Name
						FROM Information_Schema.Columns AS T2 
							WHERE 
								T2.Table_Name = T1.Table_Name
								AND T2.Column_Name NOT IN
									(
									'Created', 'Modified', 'ModifiedBy', 'RowVersion',
									'Rv', 'TimeStamp', 'Modul', 'RowGuid'
									 )          
						FOR XML PATH (''))
					, 1, 2,''
					) AS Col_Names
			FROM Information_Schema.Columns AS T1
				WHERE T1.Table_Schema = @Schema AND T1.Table_Name = @Table
				ORDER BY T1.Ordinal_Position
			)
	RETURN @k
	END
GO

IF Object_id('GetLastNumberExportByTipDoc') IS NOT NULL
  DROP FUNCTION [GetLastNumberExportByTipDoc]
GO

Create Function dbo.GetLastNumberExportByTipDoc ( @TipDoc Char(1) )
Returns Char(16)
As
Begin
	Return  (
		Select NumarDoc 
    	From Export With (UpdLock, HoldLock)
        	Where Upper(Tip) = Upper(@TipDoc) And IdDoc = 
        	(Select Max(IdDoc) From Export  With (UpdLock, HoldLock)
            	Where Upper(Tip) = Upper(@TipDoc))
		)
     
End
GO

IF Object_id('GetLastNumberIesiriByTipDoc') IS NOT NULL
  DROP FUNCTION [GetLastNumberIesiriByTipDoc]
GO

Create Function dbo.GetLastNumberIesiriByTipDoc ( @TipDoc Char(1) )
Returns Char(16)
As
Begin
	Return  (
		Select NumarDoc 
    	From Iesiri 
        	Where 
			Case
				When IsNull(@TipDoc, '') = '' And Tip In ('', 'R') Then 1           
				When IsNull(@TipDoc, '') <> '' And Tip = @TipDoc Then 1
				Else 0
			End = 1
            And IsNull(Anulat, 0) = 0
            And IdDoc = 
        		(Select Max(IdDoc) 
                From Iesiri 
            		Where 
                      Case
                          When IsNull(@TipDoc, '') = '' And Tip In ('', 'R') Then 1           
                          When IsNull(@TipDoc, '') <> '' And Tip = @TipDoc Then 1
                          Else 0
                      End = 1
					  And IsNull(Anulat, 0) = 0
                )
		)
End
GO

If Exists(Select * From sysobjects Where name ='UpdateArticoleStoc')
  DROP Procedure [UpdateArticoleStoc]
GO

Create Procedure  dbo.UpdateArticoleStoc
@IdUnicNew int,
@IdArticol int,
@lOk bit OutPut
AS
Begin Transaction
  Update Articole 
  Set Stoc = IsNull(Stoc, 0) + 
    	(
        Select Cantitate 
    	From ItemsTransactions It  
			Where It.IdArticol=Articole.Id And It.IdUnic = @IdUnicNew
		)
	Where Id = @IdArticol
	If @@RowCount = 0
    	Begin
    		RollBack
	    	RaisError('Nu a reusit Update Stoc in Articole',10,1)
			Print ' Nu a reusit Update Stoc in Articole '
       		Set @lOk =  0
            Return @lOk
    	End 
	Declare @DenArt Varchar(50) = 
    	(
        Select Denumire 
        From Articole 
    		Inner Join ItemsTransactions it On It.IdArticol  = Articole.ID
    		Where It.IdUnic = @IdUnicNew
        )
	Declare @StocMinim Decimal(14,4) = 
    	(
        Select StocMinim 
        From Articole 
			Inner Join ItemsTransactions it On It.IdArticol  = Articole.ID
    		Where It.IdUnic = @IdUnicNew
		)
	Declare @Stoc Decimal(14,4) = 
		(
        Select Stoc 
        From Articole 
			Inner Join ItemsTransactions it On It.IdArticol  = Articole.ID
			Where It.IdUnic = @IdUnicNew
		)
	If @StocMinim > @Stoc
		Begin
      		Declare @Mesaj VarChar(254)
      		Set @Mesaj = 'Stocul minim la Articolul '  + @DenArt  + ' este CRITIC!'
      		RaisError(@Mesaj,10,1)
		End
If @@Error<>0
	Begin
		RollBack Transaction
		Set @lOk = 0
	End
Else
	Begin
		Commit Transaction
		Set @lOk = 1
	End
Return @lOk
GO

If Exists(Select * From sysobjects Where name ='GetIdUnic')
  DROP Procedure [GetIdUnic]
GO

Create Procedure dbo.GetIdUnic
	@lValue int Output
As
/*
Exemplu de Utilizare
Declare @i int ;
Execute GetIdUnic @i Output
Select @i AS IdUnic     
*/
Begin
  Update Firme..Soc Set Id_Numar = IsNull(Id_Numar, 0) + 1 Where NumeDb = Db_Name()
  Select @lValue = Id_Numar	
  From Firme..Soc
  Where NumeDb = Db_Name()
End
GO

If Exists(Select * From sysobjects Where name ='sprocSearchDatabaseForText')
  DROP Procedure [sprocSearchDatabaseForText]
GO

CREATE PROC sprocSearchDatabaseForText
           @WildcardSearchTerm NVARCHAR(64)
AS
  /* The following algorithm builds on metada from INFORMATION_SCHEMA views.
 
It loops through all tables in the database
by using an outer cursor WHILE loop.
 
Within the table cursor loop, it loops through all string/text/xml columns
by using an inner cursor WHILE loop.
 
It executes a dynamic SQL search for the wildcard keyword in each column
within the nested cursor loop.
*/
  BEGIN
    SET NOCOUNT  ON
    
    DECLARE  @OutputLength VARCHAR(4) = '256',    -- SQL Server 2008+ feature
             @NolockOption CHAR(8)    = '(NOLOCK))'
    
    DECLARE  @DynamicSQL        NVARCHAR(MAX),
             @SchemaTableName   NVARCHAR(256),
             @SchemaTableColumn NVARCHAR(128),
             @SearchWildcard    NVARCHAR(128)
    
    SELECT @SearchWildcard = CHAR(39)+REPLACE(@WildcardSearchTerm,CHAR(39),
                             CHAR(39)+CHAR(39))+CHAR(39)
    
    PRINT @SearchWildcard
    
    DECLARE  @SearchResults  TABLE(
                                   SchemaTableColumn NVARCHAR(384),
                                   TextWithKeyword   NVARCHAR(MAX)
                                   )
    
    DECLARE curAllTables CURSOR  FOR
    SELECT   QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) AS SchemaTable
    FROM     INFORMATION_SCHEMA.TABLES
    WHERE    TABLE_TYPE = 'BASE TABLE'
             AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' +
                 QUOTENAME(TABLE_NAME)), 'IsMSShipped') != 1
    ORDER BY SchemaTable
    
    OPEN curAllTables
    
    FETCH NEXT FROM curAllTables
    INTO @SchemaTableName
    
    WHILE (@@FETCH_STATUS = 0) -- Outer cursor loop
      BEGIN
        PRINT @SchemaTableName
        
        SET @SchemaTableColumn = ''
        
        DECLARE curAllColumns CURSOR  FOR -- Nested cursor
        
        SELECT   QUOTENAME(COLUMN_NAME)
        FROM     INFORMATION_SCHEMA.COLUMNS
        WHERE    TABLE_NAME = PARSENAME(@SchemaTableName,1)
                 AND TABLE_SCHEMA = PARSENAME(@SchemaTableName,2)
                 AND DATA_TYPE IN ('varchar','nvarchar','char','nchar','xml')
        ORDER BY ORDINAL_POSITION
        
        OPEN curAllColumns
        
        FETCH NEXT FROM curAllColumns
        INTO @SchemaTableColumn
        
        WHILE (@@FETCH_STATUS = 0) -- Inner cursor loop (nested cursor while)
          BEGIN
            PRINT '  ' + @SchemaTableColumn
            
            SET @DynamicSQL = 'SELECT ''' + @SchemaTableName + '.' +
                @SchemaTableColumn + ''', LEFT(CONVERT(nvarchar(max),' +
                @SchemaTableColumn + '),' + @OutputLength + ')  FROM ' +
                @SchemaTableName + ' ' +
                @NolockOption + ' WHERE CONVERT(nvarchar(max),' +
                @SchemaTableColumn + ') LIKE ' + @SearchWildcard
            
            INSERT INTO @SearchResults
            EXEC sp_executesql
              @DynamicSQL
            
            FETCH NEXT FROM curAllColumns
            INTO @SchemaTableColumn
          END  -- Inner cursor loop
        
        CLOSE curAllColumns
        DEALLOCATE curAllColumns
        
        FETCH NEXT FROM curAllTables
        INTO @SchemaTableName
      END  -- Outer cursor loop
    
    CLOSE curAllTables
    DEALLOCATE curAllTables
    
    SELECT DISTINCT SchemaTableColumn,
                    TextWithKeyword
    FROM   @SearchResults
  END
GO

If Exists(Select * From sysobjects Where name ='SearchAllTables')
  DROP Procedure [SearchAllTables]
GO

CREATE PROC SearchAllTables(@SearchStr nvarchar(100))
AS
BEGIN
	-- Copyright © 2011 Vicos. All rights reserved.
	-- Purpose: To search all columns of all tables for a given search string
	-- Written by: Vicos
	-- Site: 
	-- Tested on: SQL Server 7.0 and SQL Server 2000
	-- Date modified: 28th July 2002 22:50 GMT
	-- ****************************************
	-- Also for numeric field
	-- Modified by Vicos
	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
				)
				IF ISNUMERIC(@SearchStr) = 1
				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 ('int','bigint','smallint','tinyint','decimal','float','real')
						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
		END
	END
	SELECT ColumnName, ColumnValue FROM #Results
END
GO

If Exists(Select * From sysobjects Where name ='pGetDBBackupInfo')
  DROP Procedure [pGetDBBackupInfo]
GO

Create Proc pGetDBBackupInfo
           @StartDate DateTime,
           @EndDate   DateTime,
           @Database  SYSNAME  = NULL
As
	-- Ex: dbo.pGetDBBackupInfo '2011-01-01', '2011-05-31', 'ExpertSoftwareCompany'
	Select   
			b.Database_Name,
			b.Backup_Start_Date,
			b.Backup_Finish_Date,
			b.User_Name,
			f.Logical_Name,
			f.Physical_Name,
			mf.Physical_Device_Name,
			f.File_Type,
			f.File_Size,
			b.Backup_Size
	From	MsDb.dbo.BackupFile f,
			MsDb.dbo.BackupSet b,
			MsDb.dbo.BackupMediaFamily mf
	Where	f.Backup_Set_Id = b.Backup_Set_Id
			And b.Media_Set_Id = mf.Media_Set_Id
			And b.Backup_Start_Date Between @StartDate And @EndDate
			And b.Database_Name = Coalesce(@Database, Database_Name)
	Order By	b.Database_Name, b.Backup_Start_Date
GO

If Exists(Select * From sysobjects Where name ='pGetDBRestoreInfo')
  DROP Procedure [pGetDBRestoreInfo]
GO

Create Proc pGetDBRestoreInfo
           @StartDate DateTime,
           @EndDate   DateTime,
           @Database  SysName  = NULL
As
	-- pGetDBBackupInfo '2006-07-15', '2006-07-25', 'Florin2011'
	Select
		h.destination_database_name,
		h.restore_date,
		h.user_name,
		h.restore_type,
		f.destination_phys_name,
		fg.filegroup_name
	From	
		msdb.dbo.restorehistory h,
		msdb.dbo.restorefile f,
		msdb.dbo.restorefilegroup fg
	Where
		h.restore_history_id = f.restore_history_id
		And h.restore_history_id = fg.restore_history_id
		And h.restore_date BETWEEN @StartDate And @EndDate
		And h.destination_database_name = COALESCE(@database, destination_database_name)
	Order By 
		h.destination_database_name, h.restore_date
GO

If Exists(Select * From sysobjects Where name ='sp_FindString')
  DROP Procedure [sp_FindString]
GO

--------------------------------------------------------------------
--Stored Procedure: sp_FindString
--------------------------------------------------------------------
CREATE PROCEDURE sp_FindString
		@PCAdmin varchar(2000),
		@DBIntra varchar(8000) = NULL,
		@DBExtra varchar(8000) = NULL,
		@PCIntra varchar(100)  = NULL,
		@PCExtra varchar(100)  = NULL,
		@DBAdmin int = 0,
		@DBUltra bit = 0,
		@PCUltra bit = 0
AS
/*
EXECUTE sp_FindString 'Sales'
*/
	SET NOCOUNT ON
	DECLARE @Return int
	DECLARE @Retain int
	DECLARE @Status int
	SET @Status = 0
	DECLARE @TPre varchar(10)
	DECLARE @TDo3 tinyint
	DECLARE @TDo4 tinyint
	SET @TPre = ''
	SET @TDo3 = LEN(@TPre)
	SET @TDo4 = LEN(@TPre) + 1
	DECLARE @Task varchar(2000)
	DECLARE @Rich varchar(2000)
	DECLARE @Name varchar(100)
	DECLARE @Same varchar(100)
	DECLARE @Tame varchar(100)
	DECLARE @Came varchar(100)
	DECLARE @PKey int
	DECLARE @ZKey int
	DECLARE @FKey int
	DECLARE @Rank smallint
	DECLARE @Kind varchar(20)
	DECLARE @Mask bit
	DECLARE @Bond bit
	DECLARE @Work int
	CREATE TABLE #DBAH (FKey int, Rank smallint)
	CREATE TABLE #DBAY (FKey int, Rank smallint)
	SET @Work = CASE WHEN ISNULL(@DBAdmin,0) < 2 THEN 2 ELSE @DBAdmin END - 1
	SET @Rich = REPLACE(@PCAdmin,CHAR(39),CHAR(39)+CHAR(39))
	SET @Rich = REPLACE(@Rich   ,CHAR(45)+CHAR(45),CHAR(32))
	SET @Rich = REPLACE(@Rich   ,CHAR(47)+CHAR(42),CHAR(32))
	INSERT #DBAY
	SELECT O.id, C.colid
	  FROM sysobjects AS O
	  JOIN syscolumns AS C
		ON O.id = C.id
	  JOIN systypes AS T
		ON C.xusertype = T.xusertype
	 WHERE ISNULL(OBJECTPROPERTY(O.id,'IsMSShipped'),1) = 0
	   AND RTRIM(O.type) = 'U'
	   AND LEFT(O.name,@TDo3) = @TPre
	   AND O.name NOT LIKE 'adt%'
	   AND O.name NOT LIKE '%dtproper%'
	   AND O.name NOT LIKE 'dt[_]%'
	   AND T.name     LIKE '%char'
	   AND C.length > @Work
	   AND (C.isnullable = 0 OR @DBUltra = 0)
	   AND (@DBIntra IS NULL OR CHARINDEX('|'+SUBSTRING(O.name,@TDo4,100)+'|','|'+(@DBIntra)+'|') > 0)
	   AND (@DBExtra IS NULL OR CHARINDEX('|'+SUBSTRING(O.name,@TDo4,100)+'|','|'+(@DBExtra)+'|') = 0)
	   AND (@PCIntra IS NULL OR               SUBSTRING(O.name,@TDo4,100)     LIKE @PCIntra)
	   AND (@PCExtra IS NULL OR               SUBSTRING(O.name,@TDo4,100) NOT LIKE @PCExtra)
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	DECLARE Search CURSOR FAST_FORWARD FOR
	 SELECT O.name
		  , C.name
		  , Z.FKey
		  , Z.Rank
	   FROM sysobjects AS O
	   JOIN syscolumns AS C
		 ON O.id = C.id
	   JOIN #DBAY AS Z
		 ON O.id    = Z.FKey
		AND C.colid = Z.Rank
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	OPEN Search
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	FETCH NEXT FROM Search INTO @Name, @Came, @FKey, @Rank
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	WHILE @@FETCH_STATUS = 0 AND @Status = 0
		BEGIN
		SET @Task = ' INSERT #DBAH (FKey, Rank)'
				  + ' SELECT ' + CONVERT(varchar(10),@FKey)
				  + '      , ' + CONVERT(varchar(10),@Rank)
				  + '   FROM ' + @Name
				  + '  WHERE ' + @Came + ' LIKE ' + CHAR(39) + '%' + @Rich + '%' + CHAR(39) + ' AND 0 = 0'
		IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
		IF @Status = 0 SET @Status = @Return
		FETCH NEXT FROM Search INTO @Name, @Came, @FKey, @Rank
		SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
		END
	  SELECT CASE WHEN @PCUltra = 0 THEN SUBSTRING(O.name,@TDo4,100) ELSE O.name END AS TName, C.name AS CName, COUNT(*) AS Rows
		FROM sysobjects AS O
		JOIN syscolumns AS C
		  ON O.id = C.id
		JOIN #DBAH AS Z
		  ON O.id    = Z.FKey
		 AND C.colid = Z.Rank
	GROUP BY O.name, C.name
	ORDER BY O.name, C.name
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	DROP TABLE #DBAH
	DROP TABLE #DBAY
	SET NOCOUNT OFF
	RETURN (@Status)
GO

If Exists(Select * From sysobjects Where name ='sp_ListConnections')
  DROP Procedure [sp_ListConnections]
GO

CREATE PROCEDURE dbo.sp_ListConnections
    @DBUltra bit = 0,
    @PCUltra bit = 0,
    @DBIntra varchar(8000) = NULL,
    @DBExtra varchar(8000) = NULL,
    @PCIntra varchar(100)  = NULL,
    @PCExtra varchar(100)  = NULL,
    @DBTrain    char(1)    = NULL,
    @PCTrain varchar(2000) = NULL
AS
/*
This example lists information for connections involved in blocking.
EXECUTE sp_ListConnections 1
This example lists information for connections by the SQL Agent job system.
EXECUTE sp_ListConnections 0,0,NULL,NULL,'SQLAgent%',NULL,'A'
This example lists information for active connections to the Northwind database.
EXECUTE sp_ListConnections 0,1,NULL,NULL,'Northwind',NULL,'D'
This example adds a custom message to the sysmessages table.
EXECUTE sp_addmessage 50001,16,N'The server will be restarted in 10 minutes.'
This example sends a custom message to all computers with connections to the server.
EXECUTE sp_ListConnections @PCTrain = '50001'
This example sends a literal message to computers with connections to the Northwind database.
EXECUTE sp_ListConnections 0,0,'Northwind',NULL,NULL,NULL,'D','The Northwind database will go offline in 10 minutes.'
This example kills connections to the Northwind database.
EXECUTE sp_ListConnections 0,0,'Northwind',NULL,NULL,NULL,'D','KILL @@SPID'

*/
SET NOCOUNT ON
DECLARE @Return int
DECLARE @Retain int
DECLARE @Status int
SET @Status = 0
DECLARE @Task varchar(4000)
DECLARE @Work varchar(2000)
DECLARE @Host varchar(200)
DECLARE @SPID smallint
DECLARE @SPOT smallint
SET @SPOT = CASE WHEN CHARINDEX('2000 - 8',@@VERSION,1) > 0 THEN 50 ELSE 12 END
SET @Work = REPLACE(@PCTrain,CHAR(94),CHAR(39))
IF @PCTrain IS NULL
    BEGIN
       SELECT P.spid AS [ID]
            , RTRIM(P.hostname) AS [Client]
            , RTRIM(P.loginame) AS [Login]
            , RTRIM(P.program_name) AS [Application]
            , RTRIM(O.name) AS [Database]
            , P.open_tran AS [Tran]
            , P.blocked AS [Block]
            , STR(P.waittime/1000.0,5) AS [Wait]
            , CASE P.waittype
              WHEN 0x0000 THEN ''
              WHEN 0x0001 THEN 'Lock: Schema S'
              WHEN 0x0002 THEN 'Lock: Schema M'
              WHEN 0x0003 THEN 'Lock: S'
              WHEN 0x0004 THEN 'Lock: U'
              WHEN 0x0005 THEN 'Lock: X'
              WHEN 0x0006 THEN 'Lock: IS'
              WHEN 0x0007 THEN 'Lock: IU'
              WHEN 0x0008 THEN 'Lock: IX'
              WHEN 0x0009 THEN 'Lock: SIU'
              WHEN 0x000A THEN 'Lock: SIX'
              WHEN 0x000B THEN 'Lock: UIX'
              WHEN 0x000C THEN 'Lock: BU'
              WHEN 0x000D THEN 'Lock: RangeS S'
              WHEN 0x000E THEN 'Lock: RangeS U'
              WHEN 0x000F THEN 'Lock: RangeI N'
              WHEN 0x0010 THEN 'Lock: RangeI S'
              WHEN 0x0011 THEN 'Lock: RangeI U'
              WHEN 0x0012 THEN 'Lock: RangeI X'
              WHEN 0x0013 THEN 'Lock: RangeX S'
              WHEN 0x0014 THEN 'Lock: RangeX U'
              WHEN 0x0015 THEN 'Lock: RangeX X'
              WHEN 0x0041 THEN 'DTC'
              WHEN 0x0042 THEN 'OLEDB Provider'
              WHEN 0x0081 THEN 'Writelog'
              WHEN 0x0208 THEN 'CX Packet List'
              WHEN 0x020A THEN 'Shutdown'
              WHEN 0x020B THEN 'WAITFOR'
              WHEN 0x0400 THEN 'Latch NL'
              WHEN 0x0401 THEN 'Latch KP'
              WHEN 0x0402 THEN 'Latch SH'
              WHEN 0x0403 THEN 'Latch UP'
              WHEN 0x0404 THEN 'Latch EX'
              WHEN 0x0405 THEN 'Latch DT'
              WHEN 0x0410 THEN 'PageLatch NL'
              WHEN 0x0411 THEN 'PageLatch KP'
              WHEN 0x0412 THEN 'PageLatch SH'
              WHEN 0x0413 THEN 'PageLatch UP'
              WHEN 0x0414 THEN 'PageLatch EX'
              WHEN 0x0415 THEN 'PageLatch DT'
              WHEN 0x0420 THEN 'PageIOLatch NL'
              WHEN 0x0421 THEN 'PageIOLatch KP'
              WHEN 0x0422 THEN 'PageIOLatch SH'
              WHEN 0x0423 THEN 'PageIOLatch UP'
              WHEN 0x0424 THEN 'PageIOLatch EX'
              WHEN 0x0425 THEN 'PageIOLatch DT'
              WHEN 0x0800 THEN 'Network IO'
                          ELSE 'System Task' END AS [Type]
            ,   RTRIM(P.status) AS [Status]
            ,    LEFT(P.cmd,08) AS [Command]
            , CONVERT(varchar(20),P.last_batch,20) AS [Submission]
            , CONVERT(varchar(20),P.login_time,20) AS [Connection]
         FROM master.dbo.sysprocesses AS P
         JOIN master.dbo.sysdatabases AS O
           ON P.dbid = O.dbid
    LEFT JOIN master.dbo.sysprocesses AS Z
           ON P.spid = Z.blocked
        WHERE P.spid > @SPOT
          AND (@DBIntra IS NULL OR CHARINDEX('|'+CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END+'|','|'+(@DBIntra)+'|') > 0)
          AND (@DBExtra IS NULL OR CHARINDEX('|'+CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END+'|','|'+(@DBExtra)+'|') = 0)
          AND (@PCIntra IS NULL OR               CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END     LIKE @PCIntra)
          AND (@PCExtra IS NULL OR               CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END NOT LIKE @PCExtra)
          AND CASE
              WHEN @DBUltra = 0
              THEN 1
              WHEN P.blocked != 0
              THEN 1
              WHEN Z.spid IS NOT NULL
              THEN 1
              ELSE 0 END > 0
          AND CASE
              WHEN @PCUltra = 0
              THEN 1
              WHEN P.spid != @@PROCID AND RTRIM(P.status) != 'sleeping'
              THEN 1
              WHEN P.spid != @@PROCID AND  LEFT(P.cmd,08) != 'AWAITING'
              THEN 1
              ELSE 0 END > 0
     ORDER BY [Client],[Login],[Application],[Database],[Connection],[Submission]
    SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
    END
ELSE
    BEGIN
    IF ISNUMERIC(@PCTrain) <> 0
        BEGIN
        SELECT @Work = description FROM master.dbo.sysmessages WHERE error = CONVERT(int,@PCTrain)
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        END
    IF CHARINDEX('@@SPID',@Work) = 0
        BEGIN
          DECLARE Items CURSOR FAST_FORWARD FOR
           SELECT RTRIM(P.hostname)
             FROM master.dbo.sysprocesses AS P
             JOIN master.dbo.sysdatabases AS O
               ON P.dbid = O.dbid
        LEFT JOIN master.dbo.sysprocesses AS Z
               ON P.spid = Z.blocked
            WHERE P.spid > @SPOT
              AND (@DBIntra IS NULL OR CHARINDEX('|'+CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END+'|','|'+(@DBIntra)+'|') > 0)
              AND (@DBExtra IS NULL OR CHARINDEX('|'+CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END+'|','|'+(@DBExtra)+'|') = 0)
              AND (@PCIntra IS NULL OR               CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END     LIKE @PCIntra)
              AND (@PCExtra IS NULL OR               CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END NOT LIKE @PCExtra)
              AND CASE
                  WHEN @DBUltra = 0
                  THEN 1
                  WHEN P.blocked != 0
                  THEN 1
                  WHEN Z.spid IS NOT NULL
                  THEN 1
                  ELSE 0 END > 0
              AND CASE
                  WHEN @PCUltra = 0
                  THEN 1
                  WHEN P.spid != @@PROCID AND RTRIM(P.status) != 'sleeping'
                  THEN 1
                  WHEN P.spid != @@PROCID AND  LEFT(P.cmd,08) != 'AWAITING'
                  THEN 1
                  ELSE 0 END > 0
         GROUP BY RTRIM(P.hostname)
         ORDER BY RTRIM(P.hostname)
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        OPEN Items
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        FETCH NEXT FROM Items INTO @Host
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        WHILE @@FETCH_STATUS = 0 AND @Status = 0
            BEGIN
            SET @Task = 'NET SEND ' + @Host + CHAR(32) + @Work
            EXECUTE @Return = master.dbo.xp_cmdshell @Task, NO_OUTPUT
            SET @Retain = @@ERROR
            IF @Status = 0 SET @Status = @Retain
            IF @Status = 0 SET @Status = @Return
            FETCH NEXT FROM Items INTO @Host
            SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
            END
        CLOSE Items DEALLOCATE Items
        END
    ELSE
        BEGIN
          DECLARE Items CURSOR FAST_FORWARD FOR
           SELECT P.spid
             FROM master.dbo.sysprocesses AS P
             JOIN master.dbo.sysdatabases AS O
               ON P.dbid = O.dbid
        LEFT JOIN master.dbo.sysprocesses AS Z
               ON P.spid = Z.blocked
            WHERE P.spid > @SPOT
              AND (@DBIntra IS NULL OR CHARINDEX('|'+CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END+'|','|'+(@DBIntra)+'|') > 0)
              AND (@DBExtra IS NULL OR CHARINDEX('|'+CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END+'|','|'+(@DBExtra)+'|') = 0)
              AND (@PCIntra IS NULL OR               CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END     LIKE @PCIntra)
              AND (@PCExtra IS NULL OR               CASE @DBTrain WHEN 'D' THEN RTRIM(O.name) WHEN 'A' THEN RTRIM(P.program_name) WHEN 'L' THEN RTRIM(P.loginame) ELSE RTRIM(P.hostname) END NOT LIKE @PCExtra)
              AND CASE
                  WHEN @DBUltra = 0
                  THEN 1
                  WHEN P.blocked != 0
                  THEN 1
                  WHEN Z.spid IS NOT NULL
                  THEN 1
                  ELSE 0 END > 0
              AND CASE
                  WHEN @PCUltra = 0
                  THEN 1
                  WHEN P.spid != @@PROCID AND RTRIM(P.status) != 'sleeping'
                  THEN 1
                  WHEN P.spid != @@PROCID AND  LEFT(P.cmd,08) != 'AWAITING'
                  THEN 1
                  ELSE 0 END > 0
         GROUP BY P.spid
         ORDER BY P.spid
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        OPEN Items
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        FETCH NEXT FROM Items INTO @SPID
        SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
        WHILE @@FETCH_STATUS = 0 AND @Status = 0
            BEGIN
            SET @Task = REPLACE(@Work,'@@SPID',CONVERT(varchar(5),@SPID))
            EXECUTE (@Task)
            SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
            FETCH NEXT FROM Items INTO @SPID
            SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
            END
        CLOSE Items DEALLOCATE Items
        END
    END
IF @Status = 1 OR @Status NOT BETWEEN 0 AND 50000 RAISERROR ('Windows error [%d]',16,1,@Status)
SET NOCOUNT OFF
RETURN (@Status)
GO

If Exists(Select * From sysobjects Where name ='Get_Inserted_Id')
  DROP Procedure [Get_Inserted_Id]
GO

Create Procedure Get_Inserted_Id
	@ValueIn Int,
	@ValueOut Int OUTPUT
As
Set NoCount On
Select @ValueOut=@ValueIn
GO

If Exists(Select * From sysobjects Where name ='p_Registru_Insert')
  DROP Procedure [p_Registru_Insert]
GO

Create Procedure p_Registru_Insert
	(
	@Cont_D Char(20),		
	@Cont_C Char(20),		
	@Suma Decimal(14,2),	
	@Explicatie Char(48),	
	@Id_Nota Int,
    @Data Date,
    @Validat Char(1),
	@ContD Char(20),		
	@ContC Char(20),		
    @Ndp Char(20),
    @Fel_D Char(20),    
    @Tip Char(1), 
	@Categorie Char(50),		-- 13
    @PlanB Char(16),			-- 14
    @CapitolB Char(16),			-- 15
    @ArticolB Char(16),        	-- 16	
	@IdCategorie Int,			-- 17
	@IdDifCurs Int,				-- 18    
	@Cod Char(20),				-- Cod Tert (Cont)
	@NumeTabela nVarChar(254),
    @NewId int = 0 OutPut
     )
As
Begin
	If	IsNull(@Cod, 0) <> 0
		And IsNull(@IdDifCurs, 0) <> 0
		And IsNull(@IdCategorie, 0) <> 0
		And IsNull(@Categorie, 0) <> 0
		And IsNull(@PlanB, 0) <> 0
		And IsNull(@CapitolB, 0) <> 0
		And IsNull(@ArticolB, 0) <> 0
    Begin    
		Insert Into Registru
			(Cont_D, Cont_C, Suma, Explicatie, Id_Nota, Data, Validat, ContD, ContC, Ndp, Fel_D, Tip, Categorie, PlanB, CapitolB, ArticolB, IdCategorie, IdDifCurs, Cod)
		Values        
			(@Cont_D, @Cont_C, @Suma, @Explicatie, @Id_Nota, @Data, @Validat, @ContD, @ContC, @Ndp, @Fel_D, @Tip, @Categorie, @PlanB, @CapitolB, @ArticolB, @IdCategorie, @IdDifCurs, @Cod)
    End
	If	IsNull(@Cod, 0) = 0
		And IsNull(@IdDifCurs, 0) <> 0
		And IsNull(@IdCategorie, 0) <> 0
		And IsNull(@Categorie, 0) <> 0
		And IsNull(@PlanB, 0) <> 0
		And IsNull(@CapitolB, 0) <> 0
		And IsNull(@ArticolB, 0) <> 0
    Begin    
		Insert Into Registru
			(Cont_D, Cont_C, Suma, Explicatie, Id_Nota, Data, Validat, ContD, ContC, Ndp, Fel_D, Tip, Categorie, PlanB, CapitolB, ArticolB, IdCategorie, IdDifCurs)
		Values        
			(@Cont_D, @Cont_C, @Suma, @Explicatie, @Id_Nota, @Data, @Validat, @ContD, @ContC, @Ndp, @Fel_D, @Tip, @Categorie, @PlanB, @CapitolB, @ArticolB, @IdCategorie, @IdDifCurs)
    End
	If	IsNull(@Cod, 0) = 0
		And IsNull(@IdDifCurs, 0) = 0
		And IsNull(@IdCategorie, 0) <> 0
		And IsNull(@Categorie, 0) <> 0
		And IsNull(@PlanB, 0) <> 0
		And IsNull(@CapitolB, 0) <> 0
		And IsNull(@ArticolB, 0) <> 0
    Begin    
		Insert Into Registru
			(Cont_D, Cont_C, Suma, Explicatie, Id_Nota, Data, Validat, ContD, ContC, Ndp, Fel_D, Tip, Categorie, PlanB, CapitolB, ArticolB, IdCategorie)
		Values        
			(@Cont_D, @Cont_C, @Suma, @Explicatie, @Id_Nota, @Data, @Validat, @ContD, @ContC, @Ndp, @Fel_D, @Tip, @Categorie, @PlanB, @CapitolB, @ArticolB, @IdCategorie)
    End
	If	IsNull(@Cod, 0) = 0
		And IsNull(@IdDifCurs, 0) = 0
		And IsNull(@IdCategorie, 0) = 0
		And IsNull(@Categorie, 0) = 0
		And IsNull(@PlanB, 0) <> 0
		And IsNull(@CapitolB, 0) <> 0
		And IsNull(@ArticolB, 0) <> 0
    Begin    
		Insert Into Registru
			(Cont_D, Cont_C, Suma, Explicatie, Id_Nota, Data, Validat, ContD, ContC, Ndp, Fel_D, Tip, PlanB, CapitolB, ArticolB)
		Values        
			(@Cont_D, @Cont_C, @Suma, @Explicatie, @Id_Nota, @Data, @Validat, @ContD, @ContC, @Ndp, @Fel_D, @Tip, @PlanB, @CapitolB, @ArticolB)
    End
	If	IsNull(@Cod, 0) = 0
		And IsNull(@IdDifCurs, 0) = 0
		And IsNull(@IdCategorie, 0) = 0
		And IsNull(@Categorie, 0) = 0
		And IsNull(@PlanB, 0) = 0
		And IsNull(@CapitolB, 0) = 0
		And IsNull(@ArticolB, 0) = 0
    Begin    
		Insert Into Registru
			(Cont_D, Cont_C, Suma, Explicatie, Id_Nota, Data, Validat, ContD, ContC, Ndp, Fel_D, Tip)
		Values        
			(@Cont_D, @Cont_C, @Suma, @Explicatie, @Id_Nota, @Data, @Validat, @ContD, @ContC, @Ndp, @Fel_D, @Tip)
    End
	Select @NewId = SCOPE_IDENTITY()
End
GO

If Exists(Select * From sysobjects Where name ='NextID')
  DROP Procedure [NextID]
GO

CREATE  PROCEDURE dbo.NextID 
		@TableName	sysname,
		@MandantColName	sysname,
		@IDColName	sysname,
		@MandantValue	int,
		@Range_From	int = 0,	
		@Range_To	int = 2147483647,	 
		@JustMax	bit = null	 
	AS
	SET NOCOUNT ON
	/* Exemplu de folosire in TRIGGER
		SET NOCOUNT ON
		DECLARE
			@ID_StoreAccType	int,
			@Name_StoreAccType	nvarchar(50),
			@TypeStore		bit
		SELECT
			@ID_StoreAccType	= ID_StoreAccType,
			@Name_StoreAccType	= Name_StoreAccType,
			@TypeStore		= TypeStore
		FROM inserted
		--next ID 
		EXEC @ID_StoreAccType = usp_REPL_NextID 'PROD_StoreAccTypes', NULL, 'ID_StoreAccType', NULL
		-- insert
		INSERT INTO PROD_StoreAccTypes ( ID_StoreAccType, Name_StoreAccType, TypeStore )
		VALUES (@ID_StoreAccType, @Name_StoreAccType, @TypeStore )
	*/

	DECLARE @NextID int, @SQL_Stmt nvarchar(4000), @SQL_Param nvarchar(4000)

	IF ( @MandantColName IS NOT NULL )
		SET @SQL_Stmt = 'SELECT @NextID = ISNULL (MAX(' + @IDColName + '), '
			+ CONVERT (nvarchar(10), @Range_From) + ') FROM '
			+ @TableName + ' WHERE ' + @MandantColName + ' = ' + CONVERT (nvarchar(10), @MandantValue)
			+ ' AND ' + @IDColName + ' >= ' + CONVERT (nvarchar(10), @Range_From )
			+ ' AND ' + @IDColName + ' <= ' + CONVERT (nvarchar(10), @Range_To )
	ELSE
		SET @SQL_Stmt = 'SELECT @NextID = ISNULL (MAX(' + @IDColName + '), '
			+ CONVERT (nvarchar(100), @Range_From) + ') FROM '
			+ @TableName +
			' WHERE ' + @IDColName + ' >= ' + CONVERT (nvarchar(10), @Range_From )
			+ ' AND ' + @IDColName + ' <= ' + CONVERT (nvarchar(10), @Range_To )
		SET @SQL_Param = '@NextID int OUTPUT'

	EXECUTE sp_executesql @SQL_Stmt, @SQL_Param, @NextID = @NextID OUTPUT

	IF ( @JustMax is NULL OR @JustMax = 0 )
	BEGIN
		IF @NextID < @Range_To AND @NextID > @Range_To - 100		 
			RAISERROR ('warnLimitaMaximaID', 10, 1)
		IF @NextID = @Range_To			 
			DELETE MAXDUMMY						 
		SET @NextID = @NextID + 1		 
	END
	RETURN @NextID
GO

If Exists(Select * From sysobjects Where name ='DelReg')
  DROP Procedure [DelReg]
GO

CREATE  Procedure DelReg
		@pIdNotaDels int, -- Id_Nota
		@lOk bit OutPut
As
/**********************************************************
 Creation Date:  26/12/2010
 Creation Author:  Vicos
 Purpose:  Sterge din Registru toate inregistrarile pentru 
   		   Id_Nota = @pIdNotaDels
 
 NOTE:  
	  
 Local Variables:
	  Called By: 
		  Calls:
***********************************************************/
Begin Try
	Begin Transaction
		Delete From Registru Where Id_Nota = @pIdNotaDels
	Commit Transaction;
    Set @lOk =  1;
End Try
Begin Catch
	Set @lOk =  0
	Execute [dbo].[uspPrintError];
	If XACT_STATE() <> 0 
       	RollBack Transaction;
	Execute [dbo].[uspLogError];
End Catch;
GO

If Exists(Select * From sysobjects Where name ='GetIdTipDoc')
  DROP Procedure [GetIdTipDoc]
GO

CREATE Procedure dbo.GetIdTipDoc @CodTipDoc VarChar(2)
As
Begin
	Select Id
	From TipDoc With (UpdLock, HoldLock)
		Where Upper(Cod) = Upper(@CodTipDoc)
End
GO

If Exists(Select * From sysobjects Where name ='GetSerieDefault')
  DROP Procedure [GetSerieDefault]
GO

Create Procedure dbo.GetSerieDefault @IdTipDoc Int
As
Begin
	Select 
		Descriere, 
		Sufix, 
		Prefix, 
		iBegin,
		iCurent,
		iEnd,
		Atentionare,
		Nd.Id,
		Fy.Id AS IdFiscalYear 			
	From NumerotareDocumente Nd With (UpdLock, HoldLock)
		Inner Join FiscalYears Fy On Fy.Id = nd.IdFiscalYear
		Where IdTipDoc = @IdTipDoc And Blocat = 1
End
GO

If Exists(Select * From sysobjects Where name ='NumerotareDocumente_Upd')
  DROP Procedure [NumerotareDocumente_Upd]
GO

Create Procedure NumerotareDocumente_Upd @Id int
As     
Set NoCount On
Begin Transaction
	Update NumerotareDocumente Set iCurent = IsNull(iCurent, 0)+1 
    Where Id = @Id
Commit Transaction
Return @@ERROR
GO

-- UDF GetProcTva
IF Object_id('GetProcTva') IS NOT NULL
  DROP FUNCTION [GetProcTva]
GO

CREATE FUNCTION dbo.GetProcTva (@Date Date)
RETURNS Int
AS
BEGIN
RETURN
(
SELECT 
	CASE 
		WHEN EXISTS(SELECT ModPlataTva FROM Firme..Soc WHERE Firme..Soc.NumeDb = DB_NAME() AND Firme..Soc.ModPlataTva = 3 )
			THEN 0
        ELSE
        	CASE 
            	WHEN @Date < '2010-06-30' 
					THEN 19
                ELSE 24
             END   
	END                 
)           
END
GO

-- UDF GetTipEvalGV folosit la Inchidere Luna
IF Object_id('GetTipEvalGV') IS NOT NULL
  DROP FUNCTION [GetTipEvalGV]
GO

CREATE FUNCTION dbo.GetTipEvalGV (@pCont char(20))
	RETURNS TinyInt
	AS
	BEGIN
		DECLARE @TipEval TinyInt 
		DECLARE @SocTipEval TinyInt = (SELECT ISNULL(Tip_Eval,0) FROM Firme..Soc WHERE NumeDB = Db_Name())
		IF  @SocTipEval=3 AND LEFT(@pCont,3)='371'
			IF EXISTS (SELECT ProcTva FROM Gestiuni WHERE Glob_371=@pCont AND ISNULL(ProcTva,0)>0)
				SET @TipEval=1
			ELSE
				SET @TipEval=2
		ELSE
			SET @TipEval=@SocTipEval    
		RETURN @TipEval
	END
GO

-- SELECT * FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE where VIEW_NAME='vArticoleFactura' 
--IF OBJECT_ID('ConturiArticole', 'V') IS NOT NULL

IF EXISTS(SELECT * FROM sys.views WHERE name = 'ConturiArticole' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.ConturiArticole
GO

CREATE VIEW dbo.ConturiArticole 
	AS
	SELECT 
		a.Id AS IdArticol,
		a.Denumire,
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.Cont ELSE g.glob_371 END  AS Cont,	
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.Diferente ELSE g.glob_378 END  AS Diferente,	
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.Cont4428 ELSE g.glob_4428 END  AS Cont_4428,	    
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.ContChelt ELSE g.glob_607 END  AS Cont_Che,	
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.ContVenit ELSE g.glob_707 END  AS Cont_Ven,
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN a.Pret_Aman ELSE NULL END  AS Pret_V_Tva,
		CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN a.Tva ELSE g.ProcTva  END  AS Tva
	FROM Gestiuni g
		LEFT JOIN TipuriArticole ta  
			ON g.IdTipArt = ta.Id
		INNER JOIN Articole a ON a.IdTipArt = ta.Id    
		WHERE ISNULL(ta.Sters,0) = 0
		GROUP BY 
			a.Id,
			a.Denumire,
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.Cont ELSE g.glob_371 END,	
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.Diferente ELSE g.glob_378 END,	
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.Cont4428 ELSE g.glob_4428 END,	            
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.ContChelt ELSE g.glob_607 END,	
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN ta.ContVenit ELSE g.glob_707 END,
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN a.Pret_Aman ELSE NULL END,
			CASE WHEN g.Tip_Gest = 'Cantitativ-Valorica' THEN a.Tva ELSE g.ProcTva  END
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='Forma')
	ALTER TABLE dbo.Conturi ADD [Forma] Char(2) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='IdSalariat')
	ALTER TABLE [dbo].[Conturi] ADD [IdSalariat] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='Cont_Inch')
	ALTER TABLE [dbo].[Conturi] ADD [Cont_Inch] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='Zile_Sc')
	ALTER TABLE [ComenziTransport].[Comenzi] ADD [Zile_Sc] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE ComenziTransport.Comenzi ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Garantii' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE ComenziTransport.Garantii ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Masini' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE ComenziTransport.Masini ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='ParcAuto' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE ComenziTransport.ParcAuto ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Soferi' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE ComenziTransport.Soferi ADD [iUserWorking] int NULL
GO

--If Exists ( Select * From sys.triggers Where Name = 'Soferi_tru' )

If Exists ( Select * From sys.triggers Where Name = 'Import_tri' )
	Drop Trigger [dbo].[Import_tri]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ImportTransport' AND COLUMN_NAME='Sters')
	ALTER TABLE [dbo].[ImportTransport] ADD [Sters] bit DEFAULT 0 NULL
GO

If Exists ( Select * From sys.triggers Where Name = 'Masini_trd' )
	Drop Trigger [ComenziTransport].[Masini_trd]
GO

CREATE TRIGGER [ComenziTransport].[Masini_trd] ON [ComenziTransport].[Masini]
	WITH EXECUTE AS CALLER
	FOR DELETE
	AS
	BEGIN
		DECLARE @Count int;
		SET @Count = @@ROWCOUNT;
		IF @Count = 0 
			RETURN;
		SET NOCOUNT ON;
		-- Sa nu fie folosit Idul in ComenziTransport.Comenzi  
		IF  Exists(Select * FROM Deleted WHERE Id IN (SELECT IdMasina FROM ComenziTransport.Comenzi ))
			BEGIN
				RAISERROR ('Acest Id a fost Folosit in ComenziTransport!', 16, 1)
				ROLLBACK TRANSACTION
			RETURN
		END
	END
GO

IF Object_id('ComenziTransport.Traseu') IS NULL
	CREATE TABLE [ComenziTransport].[Traseu] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [IdComanda] int NULL,
	  [CodLocalitateIncarcare] varchar(10) COLLATE Latin1_General_CI_AS NULL,
	  [LocalitateIncarcare] varchar(50) COLLATE Latin1_General_CI_AS NULL,
	  [DataIncarcarii] date NULL,
	  [CodLocDescarcare] varchar(10) COLLATE Latin1_General_CI_AS NULL,
	  [LocalitateDescarcare] varchar(50) COLLATE Latin1_General_CI_AS NULL,
	  [DataDescarcarii] date NULL,
	  [AdresaIncarcare] varchar(100) COLLATE Latin1_General_CI_AS NULL,
	  [AdresaDescarcare] varchar(100) COLLATE Latin1_General_CI_AS NULL,
	  [IdTemp] varchar(20) COLLATE Latin1_General_CI_AS NULL,
	  [iUserWorking] int NULL,
	  [Sters] bit DEFAULT 0 NULL,
	  [Created] datetime CONSTRAINT [Traseu_Created_df] DEFAULT getdate() NOT NULL,
	  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [Traseu_CreatedBy_df] DEFAULT suser_sname() NULL,
	  [Modified] datetime CONSTRAINT [Traseu_Modified_df] DEFAULT getdate() NOT NULL,
	  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [Traseu_ModifiedBy_df] DEFAULT suser_sname() NOT NULL,
	  [RowVersion] int CONSTRAINT [Traseu_RowVersion_df] DEFAULT 1 NOT NULL,
	  [FirmaIncarcare] varchar(50) COLLATE Latin1_General_CI_AS NULL,
	  [FirmaDescarcare] varchar(50) COLLATE Latin1_General_CI_AS NULL,
	  PRIMARY KEY CLUSTERED ([Id])
	)
	ON [PRIMARY]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='FirmaIncarcare')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [FirmaIncarcare] varchar(50) COLLATE Latin1_General_CI_AS NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='FirmaDescarcare')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [FirmaDescarcare] varchar(50) COLLATE Latin1_General_CI_AS NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='AdresaIncarcare')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [AdresaIncarcare] varchar(100) COLLATE Latin1_General_CI_AS NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='AdresaDescarcare')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [AdresaDescarcare] varchar(100) COLLATE Latin1_General_CI_AS NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='IdTemp')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [IdTemp] varchar(20) COLLATE Latin1_General_CI_AS NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='Referinta')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [Referinta] varchar(40) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='Greutate')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [Greutate] numeric(12, 2) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Traseu' AND COLUMN_NAME='SuprafataPodea')
	ALTER TABLE [ComenziTransport].[Traseu] ADD [SuprafataPodea] numeric(14, 2) NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'PreturiAmanunt_pk')
	ALTER TABLE [dbo].[PreturiAmanunt] ADD CONSTRAINT [PreturiAmanunt_pk] PRIMARY KEY ([Id])
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Intrari_idx')
	DROP INDEX [Intrari_idx] ON [dbo].[Intrari]
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'registru_id_nota')
	DROP INDEX [registru_id_nota] ON [dbo].[registru]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='registru' AND COLUMN_NAME='Id_Nota')
	ALTER TABLE [dbo].[registru] ALTER COLUMN [Id_Nota] int NOT NULL
GO

CREATE NONCLUSTERED INDEX [registru_id_nota] ON [dbo].[registru]
  ([Id_Nota])
WITH (
  PAD_INDEX = OFF,
  DROP_EXISTING = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Iesiri_idx')
	DROP INDEX [Iesiri_idx] ON [dbo].[Iesiri]
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Iesiri_idx2')
	DROP INDEX [Iesiri_idx2] ON [dbo].[Iesiri]
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'intrari_Total')
	DROP INDEX [intrari_Total] ON [dbo].[Intrari]
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Intrari_uq')
	ALTER TABLE [dbo].[Intrari] DROP CONSTRAINT [Intrari_uq]
GO

IF Object_id('Configurari.test') IS NOT NULL
	DROP TABLE [Configurari].[test]
GO

IF Object_id('dbo.Monitorizare') IS NOT NULL
	DROP TABLE [dbo].[Monitorizare]
GO

IF Object_id('FK_MSSQLLM$COLUMNLOG') IS NOT NULL
	ALTER TABLE [dbo].[MSSQLLM$COLUMNLOG] DROP CONSTRAINT [FK_MSSQLLM$COLUMNLOG]
GO

IF Object_id('dbo.MSSQLLM$METADATA') IS NOT NULL
	DROP TABLE [dbo].[MSSQLLM$METADATA]
GO

IF Object_id('dbo.MSSQLLM$OPERATIONLOG') IS NOT NULL
	DROP TABLE [dbo].[MSSQLLM$OPERATIONLOG]
GO

IF Object_id('dbo.MSSQLLM$COLUMNLOG') IS NOT NULL
	DROP TABLE [dbo].[MSSQLLM$COLUMNLOG]
GO

IF Object_id('dbo.MSSQLLM$COLUMNLOGDEF') IS NOT NULL
	DROP TABLE [dbo].[MSSQLLM$COLUMNLOGDEF]
GO

IF Object_id('dbo.Tranzactii') IS NOT NULL
	DROP TABLE [dbo].[Tranzactii]
GO

If Exists ( Select * From sys.triggers Where Name = 'TRI_registru_L_I' )
	Drop Trigger [dbo].[TRI_registru_L_I]
GO

If Exists ( Select * From sys.triggers Where Name = 'TRI_registru_L_U' )
	Drop Trigger [dbo].[TRI_registru_L_U]
GO

If Exists ( Select * From sys.triggers Where Name = 'TRI_registru_L_D' )
	Drop Trigger [dbo].[TRI_registru_L_D]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='bug_art' AND COLUMN_NAME='Id')
	ALTER TABLE [dbo].[bug_art] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'bug_art_pk')
	ALTER TABLE [dbo].[bug_art] ADD CONSTRAINT [bug_art_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='bug_categorii' AND COLUMN_NAME='Id')
	ALTER TABLE [dbo].[bug_categorii] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'bug_categorii_pk')	
	ALTER TABLE [dbo].[bug_categorii] ADD CONSTRAINT [bug_categorii_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='bug_planuri' AND COLUMN_NAME='Id')
	ALTER TABLE [dbo].[bug_planuri] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'bug_planuri_pk')	
	ALTER TABLE [dbo].[bug_planuri] ADD CONSTRAINT [bug_planuri_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Comenzi_pk')
	ALTER TABLE [dbo].[Comenzi] ADD CONSTRAINT [Comenzi_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'ComenziDetaliat_pk')
	ALTER TABLE [dbo].[ComenziDetaliat] ADD CONSTRAINT [ComenziDetaliat_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'ComenziTerti_pk')
	ALTER TABLE [dbo].[ComenziTerti] ADD CONSTRAINT [ComenziTerti_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='IntrariDetaliat' AND COLUMN_NAME='Id')
	ALTER TABLE [dbo].[IntrariDetaliat] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'IntrariDetaliat_pk')
	ALTER TABLE [dbo].[IntrariDetaliat] ADD CONSTRAINT [IntrariDetaliat_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ORGANIZATION' AND COLUMN_NAME='Id')
	ALTER TABLE [dbo].[ORGANIZATION] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'ORGANIZATION_pk')
	ALTER TABLE [dbo].[ORGANIZATION] ADD CONSTRAINT [ORGANIZATION_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='org_structure' AND COLUMN_NAME='Id')
	ALTER TABLE [dbo].[org_structure] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'org_structure_pk')
	ALTER TABLE [dbo].[org_structure] ADD CONSTRAINT [org_structure_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'UtilizatoriNumerotareDocumente_pk')
	ALTER TABLE [dbo].[UtilizatoriNumerotareDocumente] ADD CONSTRAINT [UtilizatoriNumerotareDocumente_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'ImportPozitiiTarifare_pk')
	ALTER TABLE [dbo].[ImportPozitiiTarifare] ADD CONSTRAINT [ImportPozitiiTarifare_pk] PRIMARY KEY ([Id])
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'ImportTransport_pk')
	ALTER TABLE [dbo].[ImportTransport] ADD CONSTRAINT [ImportTransport_pk] PRIMARY KEY ([IdDoc])
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='Semnaturi' AND COLUMN_NAME='Id')
	ALTER TABLE [Configurari].[Semnaturi] ADD [Id] int IDENTITY(1, 1) NOT NULL
GO

IF NOT EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Semnaturi_pk')
	ALTER TABLE [Configurari].[Semnaturi] ADD CONSTRAINT [Semnaturi_pk] PRIMARY KEY ([Id])
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='ExportDetaliat' AND COLUMN_NAME='ID')
	EXEC sp_rename '[dbo].[ExportDetaliat].[ID]', 'Id', 'COLUMN'
GO

--  Single use Ad-hoc plans are using 55.8 MB of procedure cache  
declare @showAdvOpts bigint;
select @showAdvOpts = cast(value_in_use as bigint) from sys.configurations where configuration_id = 518; -- show advanced options
if 0 = @showAdvOpts
begin
	exec sp_configure 'show advanced options', 1;
	reconfigure with override;
end;
exec sp_configure 'optimize for ad hoc workloads', 1;
reconfigure with override;
if 0 = @showAdvOpts
begin
	exec sp_configure 'show advanced options', 0;
	reconfigure with override;
end;

GO

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[conturi]') AND name = N'conturi_uq')
 	ALTER TABLE [dbo].[conturi] DROP CONSTRAINT [conturi_uq] 
GO

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[AmortizariDetaliat]') AND name = N'pvr_det_uq')
	ALTER TABLE [dbo].[AmortizariDetaliat] DROP CONSTRAINT [pvr_det_uq] 
GO

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[conturi]') AND name = N'conturi_uq')
	ALTER TABLE [dbo].[conturi] DROP CONSTRAINT [conturi_uq] 
GO

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[AmortizariDetaliat]') AND name = N'pvr_det_uq')
	ALTER TABLE [dbo].[AmortizariDetaliat] DROP CONSTRAINT [pvr_det_uq] 
GO

-- IF NOT EXISTS( 
--	SELECT * FROM (sysobjects INNER JOIN syscolumns ON sysobjects.id = syscolumns.id)
--	WHERE 
--	sysobjects.id = object_id(N'[dbo].[bug_art]') and 
--	OBJECTPROPERTY(sysobjects.id, N'IsUserTable') = 1 and
--	syscolumns.name = (N'Id')
--		)
--	ALTER TABLE [dbo].[bug_art] ADD [Id] int IDENTITY(1, 1) NOT NULL
-- GO 


-- IF Object_id('p_insertIntoLogTable') IS NOT NULL
--	DROP PROCEDURE p_insertIntoLogTable
-- GO 
	

-- IF Object_id('P_INSERTINTOLOGTABLEDETAILS') IS NOT NULL
--	DROP PROCEDURE P_INSERTINTOLOGTABLEDETAILS
--GO 


--If Exists ( Select * From sys.triggers Where Name = 'Comenzi_tru')
--	ALTER TABLE [ComenziTransport].[Comenzi] DISABLE TRIGGER [Comenzi_tru]
--GO 

If Exists(Select * From sysobjects Where name ='GetNumDaysInMonth')
  DROP FUNCTION [GetNumDaysInMonth]
GO

CREATE FUNCTION [dbo].[GetNumDaysInMonth] ( @myDateTime DATETIME )
 	RETURNS INT
 	AS
 	BEGIN
 		DECLARE @rtDate INT
 		SET @rtDate = 
 					CASE 
 						WHEN MONTH(@myDateTime) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
 						WHEN MONTH(@myDateTime) IN (4, 6, 9, 11) THEN 30
 						ELSE 
 							CASE 
 								WHEN (YEAR(@myDateTime) % 4 = 0 AND	YEAR(@myDateTime) % 100 != 0) OR (YEAR(@myDateTime) % 400 = 0)
 								THEN 29
 								ELSE 28 
 							END
 					END
 		RETURN @rtDate
 	END
GO

If Exists(Select * From sysobjects Where name ='ExtractInteger')
  DROP FUNCTION [ExtractInteger]	
GO

CREATE FUNCTION ExtractInteger(@String VARCHAR(2000))
	RETURNS VARCHAR(1000)
	AS
	BEGIN
	DECLARE @Count INT
	DECLARE @IntNumbers VARCHAR(1000)
	SET @Count = 0
	SET @IntNumbers = ''

	WHILE @Count <= LEN(@String)
	BEGIN
	IF SUBSTRING(@String,@Count,1) >= '0'
	AND SUBSTRING(@String,@Count,1) <= '9'
	BEGIN
	SET @IntNumbers = @IntNumbers + SUBSTRING(@String,@Count,1)
	END
	SET @Count = @Count + 1
	END

	RETURN @IntNumbers
	END
GO

IF Object_id('ConvertToChar') IS NOT NULL
  DROP FUNCTION [ConvertToChar]
GO

CREATE FUNCTION dbo.ConvertToChar(@str NVARCHAR(255))
	RETURNS NVARCHAR(255)
	AS
	/**********************************************************

	  Creation Date: 	09/04/2011
	Creation Author:	Vicos
			Purpose:	Sterge dintr-o expresie de tip SIR toate caracterele 
						care nu sunt numere sau litere 

	Local Variables:
		  Called By:	
			  Calls:
	***********************************************************/

	BEGIN

	DECLARE @pos int;
	DECLARE @chr nchar(1);

	SET @pos = PATINDEX('%[^a-z,0-9]%',@str);

	WHILE @pos > 0
	  BEGIN
		SET @chr = SUBSTRING(@str,@pos,@pos+1);
		SET @str = REPLACE(@str,@chr,'');
		SET @pos = PATINDEX('%[^a-z,0-9]%',@str);
	  END

	RETURN @str
	END
GO

-- Adaugare Coloana CreatedBy sau modificare Coloana CreatedBy din Int in nVarChar
Set NoCount On
Declare
   @TableName SysName, 
   @SchemaName SysName, 
   @SQL nVarChar(max)
-- for each table
-- 1
Declare  cTables Cursor FAST_FORWARD READ_ONLY For
	Select s.name, t.name 
	From sys.tables t
		Join sys.schemas s On t.schema_id = s.schema_id
		Where t.name Not In
             	('Audit', 'ItemsTransactions', 'ItemsDischarge', 'Caen', 'Clase', 
                'ImpozitMinim', 'Tranzactii', 'Trezorerie', 
                'FiscalYears', 'Zone', 'Adrese', 'Bic', 'Version',
                'Tva',  'WarningLevels', 
                'F101', 'D100', 'D101', 'D103', 'D300', 'D300_DecontTva', 'D390', 'D394', 'D394_Cumparari', 'D394_Vanzari',
                'PROD_MeasureUnitsClasses', 'PROD_MeasureUnits', 'PROD_PropertyItems', 'PROD_PropertyItemValues', 'PROD_PropertyClasses', 
                'DocTypeDirections', 'DocNumeration', 'DocTypes', 'DocTypeBase', 'DocTypeDirections', 'DocType', 'DocumentBase', 'EntityTypes',
                'NumerotareDocumente', 'Nationalitati', 
                'BanciTerti', 'Categorii', 'SystemParameters', 'Sucursale',
                'ErrorLog', 'xml', 'Numerators', 'SchemaAudit' )
--2 
Open cTables
--3 
Fetch cTables Into @SchemaName, @TableName   -- prime the cursor
While @@Fetch_Status = 0 
	Begin
	If Not Exists 
				(
				Select *
				From sys.tables t
					Join sys.schemas s On s.schema_id = t.schema_id
					Join sys.columns c On t.object_id = c.object_id
					Where  t.name = @TableName And s.name = @SchemaName And c.name = 'CreatedBy'
				)
		Begin                                                                                      
			Set @SQL = 'Alter Table [' + @SchemaName + '].[' + @TableName + '] Add CreatedBy nVarChar(128) Not Null Constraint ' + @TableName + '_CreatedBy_df Default(Suser_SName())'
		Exec (@SQL)
		End
	Else
		Begin                                                                                           
			Set @SQL = 'Alter Table  [' + @SchemaName + '].[' + @TableName + '] Alter Column  CreatedBy nVarChar(128) '
		-- NOT NULL constraint ' + @TableName + '_CreatedBy_df Default(Suser_SName())'
		Exec (@SQL)
		End
	Fetch cTables Into @SchemaName, @TableName   -- fetch next
End
-- 4  
Close cTables
-- 5
Deallocate  cTables
-----------------------------------------------------------------------
GO

-- Adaugare Coloana ModifiedBy sau modificare Coloana ModifiedBy din Int in nVarChar
Set NoCount On
Declare
   @TableName SysName, 
   @SchemaName SysName, 
   @SQL nVarChar(max)
-- for each table
-- 1
Declare  cTables Cursor FAST_FORWARD READ_ONLY For
	Select s.name, t.name 
	From sys.tables t
		Join sys.schemas s On t.schema_id = s.schema_id
		Where t.name Not In
             	('Audit', 'ItemsTransactions', 'ItemsDischarge', 'Caen', 'Clase', 
                'ImpozitMinim', 'Tranzactii', 'Trezorerie', 
                'FiscalYears', 'Zone', 'Adrese', 'Bic', 'Version',
                'Tva',  'WarningLevels', 
                'F101', 'D100', 'D101', 'D103', 'D300', 'D300_DecontTva', 'D390', 'D394', 'D394_Cumparari', 'D394_Vanzari',
                'PROD_MeasureUnitsClasses', 'PROD_MeasureUnits', 'PROD_PropertyItems', 'PROD_PropertyItemValues', 'PROD_PropertyClasses', 
                'DocTypeDirections', 'DocNumeration', 'DocTypes', 'DocTypeBase', 'DocTypeDirections', 'DocType', 'DocumentBase', 'EntityTypes',
                'NumerotareDocumente', 'Nationalitati', 
                'BanciTerti', 'Categorii', 'SystemParameters', 'Sucursale',
                'ErrorLog', 'xml', 'Numerators', 'SchemaAudit' )
--2 
Open cTables
--3 
Fetch cTables Into @SchemaName, @TableName   -- prime the cursor
While @@Fetch_Status = 0 
	Begin
	If Not Exists 
				(
				Select *
				From sys.tables t
					Join sys.schemas s On s.schema_id = t.schema_id
					Join sys.columns c On t.object_id = c.object_id
					Where  t.name = @TableName And s.name = @SchemaName And c.name = 'ModifiedBy'
				)
		Begin                                                                                      
			Set @SQL = 'Alter Table [' + @SchemaName + '].[' + @TableName + '] Add ModifiedBy nVarChar(128) Not Null Constraint ' + @TableName + '_ModifiedBy_df Default(Suser_SName())'
		Exec (@SQL)
		End
	Else
		Begin                                                                                           
			Set @SQL = 'Alter Table  [' + @SchemaName + '].[' + @TableName + '] Alter Column  ModifiedBy nVarChar(128) '
		-- NOT NULL constraint ' + @TableName + '_ModifiedBy_df Default(Suser_SName())'
		Exec (@SQL)
		End
	Fetch cTables Into @SchemaName, @TableName   -- fetch next
End
-- 4  
Close cTables
-- 5
Deallocate  cTables
-----------------------------------------------------------------------
GO

If Exists(Select * From sysobjects Where name ='IntrariDetaliat_UPSERT')
  DROP PROCEDURE [IntrariDetaliat_UPSERT]	
GO

Create Procedure IntrariDetaliat_UPSERT
	@ArticolB Char(16),
    @Cantitate Decimal(10,4),
    @CapitolB Char(16),
    @Categorie VarChar(50),
    @CodTva Char(5),
    @Cont VarChar(20),
    @CreatedBy nVarChar(128),
    @DenGest VarChar(30),
    @DenTipArt Char(36),
    @Denumire Char(60),
    @DenumireTva VarChar(80),
    @ExpirareArticol Date,
    @IdArticol int,
    @IdBonConsUm int,
    @IdCategorie int,
    @IdDoc int,
    @IdGest int,
    @IdLot int,
    @IdPozitie int,
    @IdTipArt int,
    @IdTva int,
    @IdUnic int,
    @NeDed Bit,
    @PlanB Char(16),
    @PretAmanunt Decimal(10,4),
    @PretStoc Decimal(10,4),
    @PreTvanzare Decimal(10,4),
    @ProcAdaos Decimal(5,2),
    @ProcDisc Decimal(11,2),
    @ProcTva TinyInt,
    @PTva_Vanz Decimal(4,2),
    @Sters Bit,
    @SumaAdaos Decimal(11,2),
    @SumaDiscount Decimal(11,2),
    @Total Decimal(11,2),
    @Tva Decimal(11,2),
    @Um VarChar(5),
	@Valoare Decimal(11,2)
As     
-- Set NoCount, XAct_Abort On
Set NoCount On
Begin Transaction
		Merge IntrariDetaliat As Old
		Using (Select @IdUnic As IdUnic) As New
	     	 ON IsNull(Old.IdUnic, 0) = IsNull(new.IdUnic, 0)
		When Matched Then
	    	Update 
	            Set 
                	ArticolB = @ArticolB,
                    Cantitate = @Cantitate,
                    CapitolB = @CapitolB,
                	Categorie = @Categorie,
                    CodTva = @CodTva,
                    Cont = @Cont,
                    DenGest = @DenGest,
                    DenTipArt = @DenTipArt,
                    Denumire = @Denumire,
                    DenumireTva = @DenumireTva,
                    ExpirareArticol = @ExpirareArticol,
                    IdArticol = @IdArticol,
                    IdBonConsUm = @IdBonConsUm,
                    IdCategorie = @IdCategorie,
                    IdGest = @IdGest,
                    IdLot = @IdLot,
                    IdPozitie = @IdPozitie,
                    IdTipArt = @IdTipArt,
                    IdTva = @IdTva,
                    NeDed = @NeDed,
                    PlanB = @PlanB,
                    PretAmanunt = @PretAmanunt,
                    PretStoc = @PretStoc,
                    PreTvanzare = @PreTvanzare,
                    ProcAdaos = @ProcAdaos,
                    ProcDisc = @ProcDisc,
                    ProcTva = @ProcTva,
                    PTva_Vanz = @PTva_Vanz,
                    Sters = @Sters,
                    SumaAdaos = @SumaAdaos,
                    SumaDiscount = @SumaDiscount,
                    Total = @Total,
                    Tva = @Tva,
                    Um = @Um,
                    Valoare = @Valoare
		When Not Matched Then
			Insert 
				(
                	ArticolB,
                    Cantitate,
                    CapitolB,
                	Categorie,
                    CodTva,
                    Cont,
                    CreatedBy,
                    DenGest,
                    DenTipArt,
                    Denumire,
                    DenumireTva,
                    ExpirareArticol,
                    IdArticol,
                    IdBonConsUm,
                    IdCategorie,
                    IdDoc,
                    IdGest,
                    IdLot,
                    IdPozitie,
                    IdTipArt,
                    IdTva,
                    IdUnic,
                    NeDed,
                    PlanB,
                    PretAmanunt,
                    PretStoc,
                    PreTvanzare,
                    ProcAdaos,
                    ProcDisc,
                    ProcTva,
                    PTva_Vanz,
                    Sters,
                    SumaAdaos,
                    SumaDiscount,
                    Total,
                    Tva,
                    Um,
                    Valoare
                	) 
			Values
					(
                    @ArticolB,
                    @Cantitate,
                    @CapitolB,
                    @Categorie,
                    @CodTva,
                    @Cont,
                    @CreatedBy,
                    @DenGest,
                    @DenTipArt,
                    @Denumire,
                    @DenumireTva,
                    @ExpirareArticol,
                    @IdArticol,
                    @IdBonConsUm,
                    @IdCategorie,
                    @IdDoc,
                    @IdGest,
                    @IdLot,
                    @IdPozitie,
                    @IdTipArt,
                    @IdTva,
                    @IdUnic,
                    @NeDed,
                    @PlanB,
                    @PretAmanunt,
                    @PretStoc,
                    @PreTvanzare,
                    @ProcAdaos,
                    @ProcDisc,
                    @ProcTva,
                    @PTva_Vanz,
                    @Sters,
                    @SumaAdaos,
                    @SumaDiscount,
                    @Total,
                    @Tva,
                    @Um,
                    @Valoare
                    );
Commit Transaction
Return @@ERROR
GO

If Exists(Select * From SysObjects Where Name ='Incarcare')
  Drop Procedure [Incarcare]	
GO

Create Procedure dbo.Incarcare
	@pIdDoc int				,			-- IdDoc
	@pNumarDoc VarChar(20)	,			-- NumarDoc
	@pDataDoc DateTime		,			-- DataDoc	        
	@pIdGest	int			,			-- Idest
	@pIdArticol	int			,			-- IdArticol
	@pCantitate Decimal(12,4),			-- Cantitate
	@pPret Decimal(10,4)	,		    -- PretUnitarReal 
	@pTipDoc Char(10)		,			-- 'IN' 		        
	@pPlan Char(10)			,			-- PlanB
	@pCapitol	Char(16)	,			-- CapitolB
	@pArticol	Char(16)	,			-- ArticolB
	@pCategorie	int,					-- IdCategorie (CenturCost sau Grupa)
	@pIdLot	Int,						-- IdLot
	@lOk Bit OutPut
	As
	Begin Transaction
		Declare @CantDescarcata Decimal(12, 4) = 0
		IF Dbo.VerificInchidereGestiune(@pDataDoc) = 0
			Begin
			   RollBack Transaction
			   RaisError('Data documentului este precedenta ultimei închideri de gestiune!',10,1)
			   Set @lOk = 0
			   Return @lOk
			End
		Set @CantDescarcata = ( Select IsNull(Sum(Cantitate),0) 
								From ItemsDischarge 
									Where IdDesc=@pIdDoc And IdArticol=@pIdArticol And (IdGest=@pIdGest Or IsNull(IdGest, 0)=0) 
		)
	  Declare @CodSoc int  = (Select CodSoc From Firme..Soc Where NumeDB = Db_Name())
	  Declare @IdUnicOld int = (Select Id_Numar From Firme..Soc Where NumeDB = Db_Name())
	  Declare @IdUnicNew int
	  Execute Firme.Dbo.IdUnic @CodSoc,@IdUnicNew Output
	  If @IdUnicNew <= @IdUnicOld
			Begin
				RollBack Transaction
				RaisError('Nu a reusit incrementarea ID Societate!',10,1)
				Set @lOk = 0
				Return @lOk
			End
		Insert Into ItemsTransactions(
							IdUnic, 
							IdDoc, 
							NumarDoc,
							Data, 
							IdGest, 
							IdArticol, 
							Cantitate, 
							CantitateRamasa, 
							Pret, 
							TipDocument, 
							SumaDescarcata, 
							PlanB, 
							CapitolB, 
							ArticolB, 
							IdCategorie,
							IdLot
							) 
			Values			(
							@IdUnicNew, 
							@pIdDoc, 
							@pNumarDoc,                         
							@pDataDoc, 
							@pIdGest, 
							@pIdArticol, 
							@pCantitate, 
							dbo.Max2(@pCantitate-@CantDescarcata, 0), 
							@pPret, 
							@pTipDoc, 
							0, 
							@pPlan, 
							@pCapitol, 
							@pArticol, 
							@pCategorie,
							@pIdLot
							)
		
		Execute dbo.UpdateArticoleStoc @IdUnicNew, @pIdArticol, @lOk OutPut
		If @lOk = 0
			Begin
				RollBack Transaction
				Return @lOk
			End
		If @@Error<>0
		Begin
			RollBack Transaction
			Set @lOk = 0
		End 
	Else
		Begin
		  Commit Transaction
		  Set @lOk = 1
	   End
	Return @lOk
GO

If Exists(Select * From sysobjects Where name ='DelMiscari')
  DROP PROCEDURE [DelMiscari]	
GO

CREATE  Procedure DelMiscari
		@pIdDels int, --IdUnicFactura
		@lOk bit OUTPUT
	AS
	/**********************************************************
	  Creation Date:  26/12/2010
	Creation Author:  Vicos
			Purpose:  Sterge din ItemsTransactions si ItemsDischarge
					  toate miscarile pentru Documentul identificat prin IdUnic			

			  NOTE:  
			  
	Local Variables:
		  Called By: 
			  Calls:
	***********************************************************/
	BEGIN TRANSACTION
		Declare @Id int 
		Declare @IdUnic int
		Declare @IdDoc int
		Declare @Data datetime 
		Declare @IdArticol int 
		Declare @IdGest int 
		Declare @Cantitate decimal(12, 4)
		Declare @CantitateRamasa decimal(12, 4) 
		Declare @Pret decimal(10, 4) 
		Declare @TipDocument char(10)
		Declare @NumarDoc char(16) 
		Declare @SumaDescarcata numeric(14, 4)
		Declare @PlanB char(16) 
		Declare @CapitolB char(16) 
		Declare @ArticolB char(16) 
		Declare @IdCategorie int 
		Declare @IdLot int     
		DECLARE  @MyIdDescarcare int
		DECLARE Miscari CURSOR LOCAL FOR Select * FROM ItemsTransactions WHERE IdDoc = @pIdDels
		OPEN Miscari
		FETCH NEXT FROM Miscari
		INTO @Id, @IdUnic, @IdDoc, @Data, @IdArticol, @IdGest, @Cantitate, @CantitateRamasa, @Pret, @TipDocument, @NumarDoc, @SumaDescarcata, @PlanB, @CapitolB, @ArticolB, @IdCategorie, @IdLot
		DECLARE @lb_Exit  bit
		SET @lb_Exit  = 0
		WHILE @@FETCH_STATUS = 0  AND (@lb_Exit = 0) 
		BEGIN
			IF dbo.VerificInchidereGestiune(@Data) = 0	SET @lb_Exit  = 1
				UPDATE Articole SET Stoc = Stoc-@Cantitate WHERE Id=@IdArticol		
				DELETE FROM ItemsTransactions WHERE Id = @Id
				IF @Cantitate < 0
					BEGIN
						SET @MyIdDescarcare  = 
							(SELECT IdDesc FROM ItemsDischarge  
								WHERE IdNew=@pIdDels AND ItemsDischarge.IdArticol=@IdArticol AND ItemsDischarge.IdGest=@IdGest	AND (IdUNew=0 OR IdUNew=@IdUnic))

						UPDATE ItemsTransactions
							SET CantitateRamasa = CantitateRamasa + 
								(SELECT Cantitate
								FROM ItemsDischarge
									WHERE ItemsDischarge.IdNew = @pIdDels AND ItemsDischarge.IdArticol=@IdArticol AND ItemsDischarge.IdGest=@IdGest
										AND (IdUNew=0 OR IdUNew=@IdUnic))                            
						FROM ItemsTransactions, ItemsDischarge
						WHERE ItemsTransactions.Id = @MyIdDescarcare;
						DELETE FROM ItemsDischarge WHERE IdNew=@pIdDels AND IdArticol=@IdArticol AND IdGest=@IdGest; 
					END  		
			FETCH NEXT FROM Miscari
			INTO @Id, @IdUnic, @IdDoc, @Data, @IdArticol, @IdGest, @Cantitate, @CantitateRamasa, @Pret, @TipDocument, @NumarDoc, @SumaDescarcata, @PlanB, @CapitolB, @ArticolB, @IdCategorie, @IdLot
		END
		CLOSE Miscari
		DEALLOCATE Miscari
	IF @@Error<>0
		BEGIN
			ROLLBACK TRANSACTION
			set @lOk =  0
		END    
	ELSE
		BEGIN
		  COMMIT TRANSACTION
		  set @lOk = 1
	   END
	RETURN @lOk
GO

If Exists(Select * From sysobjects Where name ='pDropDefaultConstraintAndColumn')
  DROP PROCEDURE [pDropDefaultConstraintAndColumn]	
GO

CREATE PROCEDURE dbo.pDropDefaultConstraintAndColumn
	@Schema VarChar(250), 
    @Table VarChar(250), 
    @Column VarChar(250)
	AS
	/**********************************************************
	  Creation Date:  05/07/2011
	Creation Author:  Vicos
			Purpose:  Sterge o coloana dintr-o tabela si constrangerile implicite

			  NOTE:  Daca am o constringere dependenta de o coloana nu pot face
              DROP pe coloana respectiva, asa ca trebuie sa aflu numele constrangerii implicite
              si sa-i fac DROP inainte de executa DROP pe coloana.
	Local Variables:
		  Called By:
			  Calls:
	***********************************************************/
	SET NOCOUNT ON
	Declare @Default SysName
	Declare @SchemaTable VarChar(500)
	If @Schema Is Null Set @Schema='dbo'
    Set @Schema = RTrim(@Schema)
    Set @Table  = RTrim(@Table)
    Set @SchemaTable = '[' + @Schema + '].[' + @Table + ']'
	If  Exists
        	( 
        	Select * From Information_Schema.Columns 
	        Where 
            	Table_Schema = @Schema 
                And Table_Name=@Table
                And Column_Name=@Column
            )			
    Begin
		Select @Default = Object_Name(cDefault)
		From SysColumns
			Where Id = Object_Id(@SchemaTable) And Name = @Column
		If @Default Is Not Null
        Begin
			Exec(N'Alter Table '  + @SchemaTable  + ' Drop Constraint ' + @Default)
		End        
	Exec(N'Alter Table ' + @SchemaTable + ' DROP COLUMN ' + @Column)
    End
	SET NOCOUNT OFF
GO

If Exists(Select * From sysobjects Where name ='sp_Crosstab')
  DROP PROCEDURE [sp_Crosstab]	
GO

--------------------------------------------------------------------
--- Stored Procedure: sp_Crosstab
--------------------------------------------------------------------
CREATE PROCEDURE dbo.sp_Crosstab
		@DBFetch varchar(4000),
		@DBWhere varchar(2000) = NULL,
		@DBPivot varchar(4000) = NULL,
		@DBField varchar(100),
		@PCField varchar(100),
		@PCBuild varchar( 20),
		@PCAdmin varchar( 20) = NULL,
		@DBAdmin int = 0,
		@DBTable varchar(100) = NULL,
		@DBWrite varchar(160) = NULL,
		@DBUltra bit = 0
	AS
	SET NOCOUNT ON
	DECLARE @Return int
	DECLARE @Retain int
	DECLARE @Status int
	SET @Status = 0
	DECLARE @TPre varchar(10)
	DECLARE @TDo3 tinyint
	DECLARE @TDo4 tinyint
	SET @TPre = 'tbl'
	SET @TDo3 = LEN(@TPre)
	SET @TDo4 = LEN(@TPre) + 1
	DECLARE @DBAE varchar(40)
	DECLARE @Task varchar(8000)
	DECLARE @Bank varchar(4000)
	DECLARE @Cash varchar(2000)
	DECLARE @Rich varchar(2000)
	DECLARE @DBAI varchar(4000)
	DECLARE @DBAO varchar(8000)
	DECLARE @DBAU varchar(2000)
	DECLARE @Name varchar(100)
	DECLARE @Same varchar(100)
	DECLARE @Home varchar(160)
	DECLARE @Some varchar(20)
	DECLARE @Work int
	DECLARE @Wink int
	SET @DBAE = '##Crosstab' + RIGHT(CONVERT(varchar(10),@@SPID+100000),5)
	SET @Task = 'IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE name = ' + CHAR(39) + @DBAE + CHAR(39) + ') DROP TABLE ' + @DBAE
	EXECUTE (@Task)
	CREATE TABLE #DBAT (Work int IDENTITY(1,1), Name varchar(100))
	SET @Bank = @TPre + @DBFetch
	IF NOT EXISTS (SELECT * FROM sysobjects WHERE RTRIM(type) = 'U' AND name = @Bank)
		BEGIN
		SET @Bank = CASE WHEN LEFT(@DBFetch,6) = 'SELECT' THEN '(' + @DBFetch + ')' ELSE @DBFetch END
		SET @Bank = REPLACE(@Bank,         CHAR(94),CHAR(39))
		SET @Bank = REPLACE(@Bank,CHAR(45)+CHAR(45),CHAR(32))
		SET @Bank = REPLACE(@Bank,CHAR(47)+CHAR(42),CHAR(32))
		END
	IF @DBWhere IS NOT NULL
		BEGIN
		SET @Cash = REPLACE(@DBWhere,'WHERE'       ,CHAR(32))
		SET @Cash = REPLACE(@Cash,         CHAR(94),CHAR(39))
		SET @Cash = REPLACE(@Cash,CHAR(45)+CHAR(45),CHAR(32))
		SET @Cash = REPLACE(@Cash,CHAR(47)+CHAR(42),CHAR(32))
		END
	SET @DBField = REPLACE(@DBField,CHAR(32),CHAR(95))
	SET @PCField = REPLACE(@PCField,CHAR(32),CHAR(95))
	SET @PCBuild = REPLACE(@PCBuild,CHAR(32),CHAR(95))
	SET @PCAdmin = REPLACE(@PCAdmin,CHAR(32),CHAR(95))
	SET @DBTable = REPLACE(@DBTable,CHAR(32),CHAR(95))
	SET @DBWrite = REPLACE(@DBWrite,CHAR(32),CHAR(95))
	SET @DBWhere = CASE WHEN @DBWhere IS NULL THEN '' ELSE ' WHERE (' + @Cash + ') AND 0 = 0' END
	SET @Some = ISNULL(@PCAdmin,'NA')
	SET @Task = 'SELECT * INTO ' + @DBAE + ' FROM ' + @Bank + ' AS T WHERE 0 = 1'
	IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
	IF @Status = 0 SET @Status = @Return
	IF @DBPivot IS NOT NULL
		BEGIN
		IF LEFT(@DBPivot,6) <> 'SELECT'
			BEGIN
			SET @Wink = 1
			SET @Work = CHARINDEX('|',(@DBPivot)+'|')
			WHILE @Work > 0
				BEGIN
				SET @Name = SUBSTRING(@DBPivot,@Wink,@Work-@Wink)
				INSERT #DBAT (Name) VALUES (@Name)
				SET @Wink = @Work + 1
				SET @Work = CHARINDEX('|',(@DBPivot)+'|',@Wink)
				END
			END
		ELSE
			BEGIN
			SET @Task = 'INSERT #DBAT (Name) ' + @DBPivot
			SET @Task = REPLACE(@Task,         CHAR(94),CHAR(39))
			SET @Task = REPLACE(@Task,CHAR(45)+CHAR(45),CHAR(32))
			SET @Task = REPLACE(@Task,CHAR(47)+CHAR(42),CHAR(32))
			IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
			IF @Status = 0 SET @Status = @Return
			END
		END
	ELSE
		BEGIN
		SET @Task = '   INSERT #DBAT (Name)'
				  + '   SELECT CONVERT(varchar(100),' + @DBField + ')'
				  + '     FROM ' + @Bank + ' AS T ' + @DBWhere
				  + ' GROUP BY CONVERT(varchar(100),' + @DBField + ')'
				  + ' ORDER BY 1'
		IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
		IF @Status = 0 SET @Status = @Return
		END
	UPDATE #DBAT SET Name = @Some WHERE Name IS NULL
	SET @DBAI = ''
	SET @DBAO = ''
	SET @Rich = ''
	 DECLARE Fields CURSOR FAST_FORWARD FOR
	  SELECT C.name
		FROM tempdb.dbo.sysobjects AS O
		JOIN tempdb.dbo.syscolumns AS C
		  ON C.id = O.id
		 AND C.name != @DBField
		 AND C.name != @PCField
		 AND O.name  = @DBAE
	ORDER BY C.colid
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	OPEN Fields
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	FETCH NEXT FROM Fields INTO @Same
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	WHILE @@FETCH_STATUS = 0 AND @Status = 0
		BEGIN
		SET @DBAI = @DBAI + ', ' +  @Same
		FETCH NEXT FROM Fields INTO @Same
		SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
		END
	CLOSE Fields DEALLOCATE Fields
	SET @DBAI = SUBSTRING(@DBAI,3,4000)
	 DECLARE Fields CURSOR FAST_FORWARD FOR
	  SELECT  Name
		FROM #DBAT
	ORDER BY  Work
	OPEN Fields
	FETCH NEXT FROM Fields INTO @Same
	WHILE @@FETCH_STATUS = 0 AND @Status = 0
		BEGIN
		IF LEN(@DBAO) < 7900 - LEN(@DBField) - LEN(@PCField) - LEN(@Same) - LEN(@Same)
			BEGIN
			SET @DBAO = @DBAO + ', ' + @PCBuild + '(CASE WHEN ISNULL(CONVERT(varchar(100),' + @DBField + '),'
							  + CHAR(39) + @Some + CHAR(39) + ') = '
							  + CHAR(39) + @Same + CHAR(39) + ' THEN '
							  + @PCField + ' ELSE NULL END) AS '
							  + CHAR(91) + @Same + CHAR(93)
			END
			ELSE
			BEGIN
			SET @Status = 50000
			END
		FETCH NEXT FROM Fields INTO @Same
		END
	CLOSE Fields DEALLOCATE Fields
	IF @DBAdmin IN (1,3) SET @Rich = @Rich + ', ' + @PCBuild + '(' + @PCField + ') AS All_' + @PCBuild
	IF @DBAdmin IN (2,3) SET @Rich = @Rich + ', COUNT('            + @PCField + ') AS All_COUNT'
	IF @DBAdmin IN (2,3) SET @Rich = @Rich + ',   MIN('            + @PCField + ') AS All_MIN'
	IF @DBAdmin IN (2,3) SET @Rich = @Rich + ',   MAX('            + @PCField + ') AS All_MAX'
	SET ANSI_WARNINGS OFF
	SET @Home = ''
	SET @Name = ''
	IF @DBTable IS NOT NULL
		BEGIN
		SET @Name = @DBTable
		IF LEFT(@Name,2) = '##'
			BEGIN
			IF @DBUltra = 0
				BEGIN
				SET @Task = 'IF EXISTS (SELECT * FROM   tempdb.dbo.sysobjects WHERE name = ' + CHAR(39) + @Name + CHAR(39) + ') DROP TABLE ' +         @Name
				IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
				IF @Status = 0 SET @Status = @Return
				END
			END
		ELSE
			BEGIN
			IF @DBWrite IS NOT NULL SET @Home = @DBWrite + '.dbo.'
			IF @DBUltra = 0
				BEGIN
				SET @Task = 'IF EXISTS (SELECT * FROM ' + @Home + 'sysobjects WHERE name = ' + CHAR(39) + @Name + CHAR(39) + ') DROP TABLE ' + @Home + @Name
				IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
				IF @Status = 0 SET @Status = @Return
				END
			END
		END
	IF @DBTable IS NOT NULL
		BEGIN
		IF @DBUltra = 0
			BEGIN
			IF @Status = 0 EXECUTE ( '   SELECT ' + @DBAI + @DBAO + @Rich
								   + '     INTO ' + @Home + @Name
								   + '     FROM ' + @Bank + ' AS T ' + @DBWhere
								   + ' GROUP BY ' + @DBAI
								   + ' ORDER BY ' + @DBAI ) SET @Return = @@ERROR
			IF @Status = 0 SET @Status = @Return
			END
		ELSE
			BEGIN
			IF @Status = 0 EXECUTE ( '   INSERT ' + @Home + @Name
								   + '   SELECT ' + @DBAI + @DBAO + @Rich
								   + '     FROM ' + @Bank + ' AS T ' + @DBWhere
								   + ' GROUP BY ' + @DBAI
								   + ' ORDER BY ' + @DBAI ) SET @Return = @@ERROR
			IF @Status = 0 SET @Status = @Return
			END
		END
	ELSE
		BEGIN
		IF @Status = 0 EXECUTE ( '   SELECT ' + @DBAI + @DBAO + @Rich
							   + '     FROM ' + @Bank + ' AS T ' + @DBWhere
							   + ' GROUP BY ' + @DBAI
							   + ' ORDER BY ' + @DBAI ) SET @Return = @@ERROR
		IF @Status = 0 SET @Status = @Return
		END
	SET ANSI_WARNINGS ON
	SET @Task = 'IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE name = ' + CHAR(39) + @DBAE + CHAR(39) + ') DROP TABLE ' + @DBAE
	EXECUTE (@Task)
	DROP TABLE #DBAT
	SET NOCOUNT OFF
	RETURN (@Status)
GO

If Exists(Select * From sysobjects Where name ='sp_FixTables')
  DROP PROCEDURE [sp_FixTables]	
GO

--------------------------------------------------------------------
-- Stored Procedure: sp_FixTables
--------------------------------------------------------------------
CREATE PROCEDURE dbo.sp_FixTables
		@DBUltra bit = 0,
		@DBIntra varchar(8000) = NULL,
		@DBExtra varchar(8000) = NULL,
		@PCIntra varchar(100)  = NULL,
		@PCExtra varchar(100)  = NULL,
		@PCAdmin varchar(7000) = NULL
	AS
	SET NOCOUNT ON
	DECLARE @Return int
	DECLARE @Retain int
	DECLARE @Status int
	SET @Status = 0
	DECLARE @TPre varchar(10)
	DECLARE @TDo3 tinyint
	DECLARE @TDo4 tinyint
	SET @TPre = ''
	SET @TDo3 = LEN(@TPre)
	SET @TDo4 = LEN(@TPre) + 1
	DECLARE @Task varchar(8000)
	DECLARE @Name varchar(100)
	DECLARE @Same varchar(100)
	DECLARE @Pick varchar(100)
	DECLARE @Work varchar(10)
	DECLARE @Wish varchar(10)
	IF @PCAdmin IS NULL SET @PCAdmin = 'UPDATE STATISTICS * WITH FULLSCAN EXECUTE sp_recompile ^*^' 
	   SET @PCAdmin = REPLACE(@PCAdmin,CHAR(94),CHAR(39))
	-- SET @PCAdmin = REPLACE(@PCAdmin,CHAR(96),CHAR(39))
	 DECLARE Tables CURSOR FAST_FORWARD FOR
	  SELECT O.name,
			 U.name,
			 CONVERT(varchar(10),O.id),
			 SUBSTRING(O.name,@TDo4,100)
		FROM sysobjects AS O
		JOIN sysusers AS U
		  ON O.uid = U.uid
	   WHERE ISNULL(OBJECTPROPERTY(O.id,'IsMSShipped'),1) = 0
		 AND RTRIM(O.type) = 'U'
		 AND LEFT(O.name,@TDo3) = @TPre
		 AND O.name NOT LIKE 'adt%'
		 AND O.name NOT LIKE '%dtproper%'
		 AND O.name NOT LIKE 'dt[_]%'
		 AND (@DBIntra IS NULL OR CHARINDEX('|'+SUBSTRING(O.name,@TDo4,100)+'|','|'+(@DBIntra)+'|') > 0)
		 AND (@DBExtra IS NULL OR CHARINDEX('|'+SUBSTRING(O.name,@TDo4,100)+'|','|'+(@DBExtra)+'|') = 0)
		 AND (@PCIntra IS NULL OR               SUBSTRING(O.name,@TDo4,100)     LIKE @PCIntra)
		 AND (@PCExtra IS NULL OR               SUBSTRING(O.name,@TDo4,100) NOT LIKE @PCExtra)
	ORDER BY O.name
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	OPEN Tables
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	FETCH NEXT FROM Tables INTO @Name, @Same, @Work, @Pick
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	IF @DBUltra = 0
		BEGIN
		WHILE @@FETCH_STATUS = 0 AND @Status = 0
			BEGIN
			SET @Task = @PCAdmin
			SET @Task = REPLACE(@Task,CHAR(42),@Name)
			SET @Task = REPLACE(@Task,CHAR(36),@Same)
			SET @Task = REPLACE(@Task,CHAR(35),@Work)
			SET @Task = REPLACE(@Task,CHAR(38),@Pick)
			PRINT @Task
			FETCH NEXT FROM Tables INTO @Name, @Same, @Work, @Pick
			SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
			END
		END
	ELSE
		BEGIN
		WHILE @@FETCH_STATUS = 0 AND @Status = 0
			BEGIN
			SET @Task = @PCAdmin
			SET @Task = REPLACE(@Task,CHAR(42),@Name)
			SET @Task = REPLACE(@Task,CHAR(36),@Same)
			SET @Task = REPLACE(@Task,CHAR(35),@Work)
			SET @Task = REPLACE(@Task,CHAR(38),@Pick)
			IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
			IF @Status = 0 SET @Status = @Return
			FETCH NEXT FROM Tables INTO @Name, @Same, @Work, @Pick
			SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
			END
		END
	CLOSE Tables DEALLOCATE Tables
	SET NOCOUNT OFF
	RETURN (@Status)
GO

If Exists(Select * From sysobjects Where name ='sp_FindString')
  DROP PROCEDURE [sp_FindString]	
GO

--------------------------------------------------------------------
--Stored Procedure: sp_FindString
--------------------------------------------------------------------
CREATE PROCEDURE sp_FindString
		@PCAdmin varchar(2000),
		@DBIntra varchar(8000) = NULL,
		@DBExtra varchar(8000) = NULL,
		@PCIntra varchar(100)  = NULL,
		@PCExtra varchar(100)  = NULL,
		@DBAdmin int = 0,
		@DBUltra bit = 0,
		@PCUltra bit = 0
	AS
	SET NOCOUNT ON
	DECLARE @Return int
	DECLARE @Retain int
	DECLARE @Status int
	SET @Status = 0
	DECLARE @TPre varchar(10)
	DECLARE @TDo3 tinyint
	DECLARE @TDo4 tinyint
	SET @TPre = ''
	SET @TDo3 = LEN(@TPre)
	SET @TDo4 = LEN(@TPre) + 1
	DECLARE @Task varchar(2000)
	DECLARE @Rich varchar(2000)
	DECLARE @Name varchar(100)
	DECLARE @Same varchar(100)
	DECLARE @Tame varchar(100)
	DECLARE @Came varchar(100)
	DECLARE @PKey int
	DECLARE @ZKey int
	DECLARE @FKey int
	DECLARE @Rank smallint
	DECLARE @Kind varchar(20)
	DECLARE @Mask bit
	DECLARE @Bond bit
	DECLARE @Work int
	CREATE TABLE #DBAH (FKey int, Rank smallint)
	CREATE TABLE #DBAY (FKey int, Rank smallint)
	SET @Work = CASE WHEN ISNULL(@DBAdmin,0) < 2 THEN 2 ELSE @DBAdmin END - 1
	SET @Rich = REPLACE(@PCAdmin,CHAR(39),CHAR(39)+CHAR(39))
	SET @Rich = REPLACE(@Rich   ,CHAR(45)+CHAR(45),CHAR(32))
	SET @Rich = REPLACE(@Rich   ,CHAR(47)+CHAR(42),CHAR(32))
	INSERT #DBAY
	SELECT O.id, C.colid
	  FROM sysobjects AS O
	  JOIN syscolumns AS C
		ON O.id = C.id
	  JOIN systypes AS T
		ON C.xusertype = T.xusertype
	 WHERE ISNULL(OBJECTPROPERTY(O.id,'IsMSShipped'),1) = 0
	   AND RTRIM(O.type) = 'U'
	   AND LEFT(O.name,@TDo3) = @TPre
	   AND O.name NOT LIKE 'adt%'
	   AND O.name NOT LIKE '%dtproper%'
	   AND O.name NOT LIKE 'dt[_]%'
	   AND T.name     LIKE '%char'
	   AND C.length > @Work
	   AND (C.isnullable = 0 OR @DBUltra = 0)
	   AND (@DBIntra IS NULL OR CHARINDEX('|'+SUBSTRING(O.name,@TDo4,100)+'|','|'+(@DBIntra)+'|') > 0)
	   AND (@DBExtra IS NULL OR CHARINDEX('|'+SUBSTRING(O.name,@TDo4,100)+'|','|'+(@DBExtra)+'|') = 0)
	   AND (@PCIntra IS NULL OR               SUBSTRING(O.name,@TDo4,100)     LIKE @PCIntra)
	   AND (@PCExtra IS NULL OR               SUBSTRING(O.name,@TDo4,100) NOT LIKE @PCExtra)
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	DECLARE Search CURSOR FAST_FORWARD FOR
	 SELECT O.name
		  , C.name
		  , Z.FKey
		  , Z.Rank
	   FROM sysobjects AS O
	   JOIN syscolumns AS C
		 ON O.id = C.id
	   JOIN #DBAY AS Z
		 ON O.id    = Z.FKey
		AND C.colid = Z.Rank
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	OPEN Search
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	FETCH NEXT FROM Search INTO @Name, @Came, @FKey, @Rank
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	WHILE @@FETCH_STATUS = 0 AND @Status = 0
		BEGIN
		SET @Task = ' INSERT #DBAH (FKey, Rank)'
				  + ' SELECT ' + CONVERT(varchar(10),@FKey)
				  + '      , ' + CONVERT(varchar(10),@Rank)
				  + '   FROM ' + @Name
				  + '  WHERE ' + @Came + ' LIKE ' + CHAR(39) + '%' + @Rich + '%' + CHAR(39) + ' AND 0 = 0'
		IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
		IF @Status = 0 SET @Status = @Return
		FETCH NEXT FROM Search INTO @Name, @Came, @FKey, @Rank
		SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
		END
	  SELECT CASE WHEN @PCUltra = 0 THEN SUBSTRING(O.name,@TDo4,100) ELSE O.name END AS TName, C.name AS CName, COUNT(*) AS Rows
		FROM sysobjects AS O
		JOIN syscolumns AS C
		  ON O.id = C.id
		JOIN #DBAH AS Z
		  ON O.id    = Z.FKey
		 AND C.colid = Z.Rank
	GROUP BY O.name, C.name
	ORDER BY O.name, C.name
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	DROP TABLE #DBAH
	DROP TABLE #DBAY
	SET NOCOUNT OFF
	RETURN (@Status)
GO

If Exists(Select * From sysobjects Where name ='sp_ListObjects')
  DROP PROCEDURE [sp_ListObjects]	
GO

--------------------------------------------------------------------
-- Stored Procedure: sp_ListObjects
--------------------------------------------------------------------
CREATE PROCEDURE dbo.sp_ListObjects
		@DBIntra varchar(100) = NULL,
		@DBExtra varchar(100) = NULL,
		@DBUltra bit = 0
	AS
	SET NOCOUNT ON
	DECLARE @Return int
	DECLARE @Retain int
	DECLARE @Status int
	SET @Status = 0
	DECLARE @TPre varchar(10)
	DECLARE @TDo3 tinyint
	DECLARE @TDo4 tinyint
	SET @TPre = ''
	SET @TDo3 = LEN(@TPre)
	SET @TDo4 = LEN(@TPre) + 1
	DECLARE @icrdate datetime
	DECLARE @itype char(2)
	SET @itype = 'I'
	IF @DBIntra IS NULL AND @DBExtra IS NULL
		BEGIN
		IF @DBUltra = 0 SET @DBIntra = 'V|P|FN|IF|TF|TR'
		ELSE            SET @DBIntra = 'U|K|F|C|D|' + RTRIM(@itype)
		END
	   SELECT        O.type     AS Type
			, ISNULL(T.name,'') AS Parent
			,        O.name     AS Object
			, ISNULL(CONVERT(varchar(30),O.crdate,120),'') AS Creation
		 FROM sysobjects AS O
	LEFT JOIN sysobjects AS T
		   ON O.parent_obj = T.id
		WHERE ISNULL(OBJECTPROPERTY(O.id,'IsMSShipped'),1) = 0
		  AND O.name NOT LIKE '%dtproper%'
		  AND O.name NOT LIKE 'dt[_]%'
		  AND (@DBIntra IS NULL OR CHARINDEX('|'+RTRIM(O.type)+'|','|'+(@DBIntra)+'|') > 0)
		  AND (@DBExtra IS NULL OR CHARINDEX('|'+RTRIM(O.type)+'|','|'+(@DBExtra)+'|') = 0)
		UNION ALL
	   SELECT        @itype     AS Type
			, ISNULL(O.name,'') AS Parent
			,        I.name     AS Object
			, ISNULL(CONVERT(varchar(30),@icrdate,120),'') AS Creation
		 FROM sysobjects AS O
		 JOIN sysindexes AS I
		   ON O.id = I.id
		WHERE ISNULL(OBJECTPROPERTY(O.id,'IsMSShipped'),1) = 0
		  AND RTRIM(O.type) = 'U'
		  AND LEFT(O.name,@TDo3) = @TPre
		  AND O.name NOT LIKE '%dtproper%'
		  AND O.name NOT LIKE 'dt[_]%'
		  AND I.indid BETWEEN 1 AND 254
		  AND LEFT(I.name,8) <> '_WA_Sys_'
		  AND (@DBIntra IS NULL OR CHARINDEX('|'+RTRIM(@itype)+'|','|'+(@DBIntra)+'|') > 0)
		  AND (@DBExtra IS NULL OR CHARINDEX('|'+RTRIM(@itype)+'|','|'+(@DBExtra)+'|') = 0)
	 ORDER BY Type, Parent, Object
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	SET NOCOUNT OFF
	RETURN (@Status)
GO

If Exists(Select * From sysobjects Where name ='sp_FixObjects')
	DROP PROCEDURE [sp_FixObjects]		
GO

--------------------------------------------------------------------
-- Stored Procedure: sp_FixObjects
--------------------------------------------------------------------
CREATE PROCEDURE dbo.sp_FixObjects
		@DBUltra bit = 0,
		@DBIntra varchar(8000) = NULL,
		@DBExtra varchar(8000) = NULL,
		@PCIntra varchar(100)  = NULL,
		@PCExtra varchar(100)  = NULL,
		@PCAdmin varchar(7000) = NULL
	AS
	SET NOCOUNT ON
	DECLARE @Return int
	DECLARE @Retain int
	DECLARE @Status int
	SET @Status = 0
	DECLARE @Task varchar(8000)
	DECLARE @Name varchar(100)
	DECLARE @Same varchar(100)
	DECLARE @Pick varchar(100)
	DECLARE @Work varchar(10)
	DECLARE @Wish varchar(10)
	IF @PCAdmin IS NULL SET @PCAdmin = 'IF ^$^ <> ^dbo^ EXECUTE sp_changeobjectowner ^$.*^,^dbo^' 
	   SET @PCAdmin = REPLACE(@PCAdmin,CHAR(94),CHAR(39))
	-- SET @PCAdmin = REPLACE(@PCAdmin,CHAR(96),CHAR(39))
	 DECLARE DBItems CURSOR FAST_FORWARD FOR
	  SELECT O.name,
			 U.name,
			 CONVERT(varchar(10),O.id),
			 CASE O.type
			 WHEN 'U ' THEN 'TABLE'
			 WHEN 'V ' THEN 'VIEW'
			 WHEN 'P ' THEN 'PROCEDURE'
			 WHEN 'FN' THEN 'FUNCTION'
			 WHEN 'IF' THEN 'FUNCTION'
			 WHEN 'TF' THEN 'FUNCTION'
					   ELSE 'FUNCTION' END
		FROM sysobjects AS O
		JOIN sysusers AS U
		  ON O.uid = U.uid
	   WHERE ISNULL(OBJECTPROPERTY(O.id,'IsMSShipped'),1) = 0
		 AND O.type IN ('U ','V ','P ','FN','IF','TF')
		 AND O.name NOT LIKE 'adt%'
		 AND O.name NOT LIKE '%dtproper%'
		 AND O.name NOT LIKE 'dt[_]%'
		 AND (@DBIntra IS NULL OR CHARINDEX('|'+O.name+'|','|'+(@DBIntra)+'|') > 0)
		 AND (@DBExtra IS NULL OR CHARINDEX('|'+O.name+'|','|'+(@DBExtra)+'|') = 0)
		 AND (@PCIntra IS NULL OR               O.name     LIKE @PCIntra)
		 AND (@PCExtra IS NULL OR               O.name NOT LIKE @PCExtra)
	ORDER BY O.name
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	OPEN DBItems
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	FETCH NEXT FROM DBItems INTO @Name, @Same, @Work, @Pick
	SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
	IF @DBUltra = 0
		BEGIN
		WHILE @@FETCH_STATUS = 0 AND @Status = 0
			BEGIN
			SET @Task = @PCAdmin
			SET @Task = REPLACE(@Task,CHAR(42),@Name)
			SET @Task = REPLACE(@Task,CHAR(36),@Same)
			SET @Task = REPLACE(@Task,CHAR(35),@Work)
			SET @Task = REPLACE(@Task,CHAR(38),@Pick)
			PRINT @Task
			FETCH NEXT FROM DBItems INTO @Name, @Same, @Work, @Pick
			SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
			END
		END
	ELSE
		BEGIN
		WHILE @@FETCH_STATUS = 0 AND @Status = 0
			BEGIN
			SET @Task = @PCAdmin
			SET @Task = REPLACE(@Task,CHAR(42),@Name)
			SET @Task = REPLACE(@Task,CHAR(36),@Same)
			SET @Task = REPLACE(@Task,CHAR(35),@Work)
			SET @Task = REPLACE(@Task,CHAR(38),@Pick)
			IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
			IF @Status = 0 SET @Status = @Return
			FETCH NEXT FROM DBItems INTO @Name, @Same, @Work, @Pick
			SET @Retain = @@ERROR IF @Status = 0 SET @Status = @Retain
			END
		END
	CLOSE DBItems DEALLOCATE DBItems
	SET NOCOUNT OFF
	RETURN (@Status)
GO

--  The SET NOCOUNT ON connection option is not being used
declare @value bigint;
select @value = cast(value_in_use as bigint) from sys.configurations where configuration_id = 1534; -- user options
if 0 = (@value & 512)
begin
	set @value = @value | 512;
	exec sp_configure 'user options', @value;
	reconfigure with override;
end;

GO

If Exists ( Select * From sys.triggers Where Name = 'Comenzi_tru')
	ALTER TABLE [ComenziTransport].[Comenzi] DISABLE TRIGGER [Comenzi_tru]
GO

EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Comenzi], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Comenzi], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Comenzi], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Masini], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Masini], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Masini], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [ParcAuto], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [ParcAuto], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [ParcAuto], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Soferi], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Soferi], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Soferi], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Garantii], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Garantii], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [ComenziTransport], [Garantii], [DataCrearii]

GO

IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Agenti' AND COLUMN_NAME='ID')
	EXEC sp_rename '[dbo].[Agenti].[ID]', 'Id', 'COLUMN'
GO

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Agenti], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Agenti], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Agenti], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Articole], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Articole], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Articole], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Gestiuni], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Gestiuni], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Gestiuni], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [SystemParameters], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [SystemParameters], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [SystemParameters], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Iesiri], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Iesiri], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Iesiri], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Intrari], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Intrari], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Intrari], [DataCrearii]

GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Agenti' AND COLUMN_NAME='Tip')
	ALTER TABLE [dbo].[Agenti] ADD [Tip] Char(1) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Agenti' AND COLUMN_NAME='cnp')
	ALTER TABLE [dbo].[Agenti] ADD [cnp] char(13) NULL
GO

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Agenti], [IsAgent]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Agenti], [IsDelegat]
GO

IF Object_id('dbo.UtilizatoriAgenti') IS NOT NULL
	DROP TABLE [dbo].[UtilizatoriAgenti]
GO

CREATE TABLE [dbo].[UtilizatoriAgenti] (
  [Id] int IDENTITY(1, 1) NOT NULL,
  [IdAgenti] int NOT NULL,
  [IdUser] int NOT NULL,
  [Created] datetime CONSTRAINT [UtilizatoriAgenti_Created_df] DEFAULT getdate() NOT NULL,
  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [UtilizatoriAgenti_CreatedBy_df] DEFAULT suser_sname() NOT NULL,
  [Modified] datetime CONSTRAINT [UtilizatoriAgenti_Modified_df] DEFAULT getdate() NOT NULL,
  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [UtilizatoriAgenti_ModifiedBy_df] DEFAULT suser_sname() NOT NULL,
  [RowVersion] int CONSTRAINT [UtilizatoriAgenti_RowVersion_df] DEFAULT 1 NOT NULL,
  CONSTRAINT [UtilizatoriAgenti_pk] PRIMARY KEY CLUSTERED ([Id])
)
ON [PRIMARY]
GO

CREATE TRIGGER [dbo].[UtilizatoriAgenti_Audit_Insert] ON [dbo].[UtilizatoriAgenti]
WITH EXECUTE AS CALLER
FOR INSERT
NOT FOR REPLICATION
AS
 SET NoCount On 
 SET ARITHABORT ON 
 -- generated by AutoAudit on Jun 17 2011  1:53PM
 -- created by Paul Nielsen 
 -- www.SQLServerBible.com 

DECLARE @AuditTime DATETIME
SET @AuditTime = GetDate()

 Begin Try 
 -- capture SQL Statement
 DECLARE @ExecStr varchar(50), @UserSQL nvarchar(max)
 DECLARE  @inputbuffer TABLE
 (EventType nvarchar(30), Parameters int, EventInfo nvarchar(max))
 SET @ExecStr = 'DBCC INPUTBUFFER(@@SPID) with no_infomsgs'
 INSERT INTO @inputbuffer
   EXEC (@ExecStr)
 SELECT @UserSQL = EventInfo FROM @inputbuffer


   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, NewValue, RowVersion)
   SELECT @AuditTime, COALESCE(Inserted.CreatedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(), 'dbo.UtilizatoriAgenti', 'i', @UserSQL, 
 Inserted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Order Number for an Order Detail Line)
        '[Id]', Cast(Inserted.[Id] as VARCHAR(50)), 1
          FROM Inserted
          WHERE Inserted.[Id] is not null

-----

 -- Update the Created and Modified columns
   UPDATE [dbo].[UtilizatoriAgenti]
     SET Created  = @AuditTime, 
         CreatedBy  = COALESCE(Inserted.CreatedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), 
         Modified = @AuditTime, 
         ModifiedBy  = COALESCE(Inserted.CreatedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), 
        [RowVersion] =  1
     FROM [dbo].[UtilizatoriAgenti]
       JOIN Inserted
         ON [UtilizatoriAgenti].[Id] = Inserted.[Id]

-----

 End Try 
 Begin Catch 
   DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT;
   SET @ErrorMessage = ERROR_MESSAGE();  
   SET @ErrorSeverity = ERROR_SEVERITY(); 
   SET @ErrorState = ERROR_STATE();  
   RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState) with log;
 End Catch
GO

CREATE TRIGGER [dbo].[UtilizatoriAgenti_Audit_Update] ON [dbo].[UtilizatoriAgenti]
WITH EXECUTE AS CALLER
FOR UPDATE
NOT FOR REPLICATION
AS
 SET NoCount On 
 -- generated by AutoAudit on Jun 17 2011  1:53PM
 -- created by Paul Nielsen 
 -- www.SQLServerBible.com 

DECLARE @AuditTime DATETIME, @IsDirty BIT
SET @AuditTime = GetDate()

SET @IsDirty = 0

 Begin Try 
 -- capture SQL Statement
 DECLARE @ExecStr varchar(50), @UserSQL nvarchar(max)
 DECLARE  @inputbuffer TABLE
 (EventType nvarchar(30), Parameters int, EventInfo nvarchar(max))
 SET @ExecStr = 'DBCC INPUTBUFFER(@@SPID) with no_infomsgs'
 INSERT INTO @inputbuffer
   EXEC (@ExecStr)
 SELECT @UserSQL = EventInfo FROM @inputbuffer


   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, NewValue, RowVersion)
   SELECT  @AuditTime, COALESCE(Inserted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(), 'dbo.UtilizatoriAgenti', 'u', @UserSQL, 
 Convert(VARCHAR(50), Inserted.[Id]),
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Order Number for an Order Detail Line)
        '[IdAgenti]', Convert(VARCHAR(50), Deleted.[IdAgenti]),  Convert(VARCHAR(50), Inserted.[IdAgenti]),
 DELETED.Rowversion + 1
          FROM Inserted
             JOIN Deleted
               ON Inserted.[Id] = Deleted.[Id]
               AND ISNULL(Inserted.[IdAgenti],'') <> ISNULL(Deleted.[IdAgenti],'')
   IF @@RowCount > 0 SET @IsDirty = 1
-----

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, NewValue, RowVersion)
   SELECT  @AuditTime, COALESCE(Inserted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(), 'dbo.UtilizatoriAgenti', 'u', @UserSQL, 
 Convert(VARCHAR(50), Inserted.[Id]),
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Order Number for an Order Detail Line)
        '[IdUser]', Convert(VARCHAR(50), Deleted.[IdUser]),  Convert(VARCHAR(50), Inserted.[IdUser]),
 DELETED.Rowversion + 1
          FROM Inserted
             JOIN Deleted
               ON Inserted.[Id] = Deleted.[Id]
               AND ISNULL(Inserted.[IdUser],'') <> ISNULL(Deleted.[IdUser],'')
   IF @@RowCount > 0 SET @IsDirty = 1
-----

-----

 -- Update the Modified date
 IF @IsDirty = 1
   UPDATE [dbo].[UtilizatoriAgenti]
     SET Modified = @AuditTime, 
         ModifiedBy  = COALESCE(Inserted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), 
        [RowVersion] = [UtilizatoriAgenti].[RowVersion] + 1 
     FROM [dbo].[UtilizatoriAgenti]
       JOIN Inserted
         ON [UtilizatoriAgenti].[Id] = Inserted.[Id]

-----

 End Try 
 Begin Catch 
   DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT;
   SET @ErrorMessage = ERROR_MESSAGE();  
   SET @ErrorSeverity = ERROR_SEVERITY(); 
   SET @ErrorState = ERROR_STATE();  
   RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState) with log;
 End Catch
GO

CREATE TRIGGER [dbo].[UtilizatoriAgenti_Audit_Delete] ON [dbo].[UtilizatoriAgenti]
WITH EXECUTE AS CALLER
FOR DELETE
NOT FOR REPLICATION
AS
 SET NoCount On 
 -- generated by AutoAudit on Jun 17 2011  1:53PM
 -- created by Paul Nielsen 
 -- www.SQLServerBible.com 

DECLARE @AuditTime DATETIME
SET @AuditTime = GetDate()

 -- capture SQL Statement
 DECLARE @ExecStr varchar(50), @UserSQL nvarchar(max)
 DECLARE  @inputbuffer TABLE
 (EventType nvarchar(30), Parameters int, EventInfo nvarchar(max))
 SET @ExecStr = 'DBCC INPUTBUFFER(@@SPID) with no_infomsgs'
 INSERT INTO @inputbuffer
   EXEC (@ExecStr)
 SELECT @UserSQL = EventInfo FROM @inputbuffer


 Begin Try 
   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[Id]', Convert(VARCHAR(50), Deleted.[Id]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[Id] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[IdAgenti]', Convert(VARCHAR(50), Deleted.[IdAgenti]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[IdAgenti] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[IdUser]', Convert(VARCHAR(50), Deleted.[IdUser]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[IdUser] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[Created]', Convert(VARCHAR(50), Deleted.[Created]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[Created] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[CreatedBy]', Convert(VARCHAR(50), Deleted.[CreatedBy]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[CreatedBy] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[Modified]', Convert(VARCHAR(50), Deleted.[Modified]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[Modified] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[ModifiedBy]', Convert(VARCHAR(50), Deleted.[ModifiedBy]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[ModifiedBy] is not null

   INSERT dbo.Audit (AuditDate, SysUser, Application, HostName, TableName, Operation, SQLStatement, PrimaryKey, RowDescription, SecondaryRow, ColumnName, OldValue, Rowversion)
   SELECT  @AuditTime, COALESCE(deleted.ModifiedBy, (SELECT TOP 1 Nume FROM Firme.dbo.Utilizatori WHERE sStationConnected = Host_Name())), APP_NAME(), Host_Name(),'dbo.UtilizatoriAgenti', 'd', @UserSQL, 
 deleted.[Id],
        NULL,     -- Row Description (e.g. Order Number)
        NULL,     -- Secondary Row Value (e.g. Oder Number for an Order Detail Line)
        '[RowVersion]', Convert(VARCHAR(50), Deleted.[RowVersion]),  deleted.Rowversion           FROM deleted
          WHERE deleted.[RowVersion] is not null

 End Try 
 Begin Catch 
   DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT;
   SET @ErrorMessage = ERROR_MESSAGE();  
   SET @ErrorSeverity = ERROR_SEVERITY(); 
   SET @ErrorState = ERROR_STATE();  
   RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState) with log;
 End Catch
GO

IF EXISTS(SELECT * FROM sys.sysindexes WHERE name = 'Export_idx')
	DROP INDEX [Export_idx] ON [dbo].[Export]
GO

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Export], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Export], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Export], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Import], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Import], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Import], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [ImportTransport], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [ImportTransport], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [ImportTransport], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Conturi], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Conturi], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Conturi], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [CheltuieliVenitAvans], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [CheltuieliVenitAvans], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [CheltuieliVenitAvans], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [NotePredare], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [NotePredare], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [NotePredare], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [NotePredareDetaliat], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [NotePredareDetaliat], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [NotePredareDetaliat], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [BonuriConsum], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [BonuriConsum], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [BonuriConsum], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [BonuriConsumDetaliat], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [BonuriConsumDetaliat], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [BonuriConsumDetaliat], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Casari], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Casari], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Casari], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [CasariDetaliat], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [CasariDetaliat], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [CasariDetaliat], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Inventar], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Inventar], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Inventar], [DataCrearii]

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Registru], [Modul]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Registru], [ModifiedDate]
EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [Registru], [DataCrearii]

GO

If Exists ( Select * From sys.triggers Where Name = 'articole_tru')
	DROP TRIGGER [dbo].[articole_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'BonuriConsumDetaliat_tru')
	DROP TRIGGER [dbo].[BonuriConsumDetaliat_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Casari_tru' )
	DROP TRIGGER [dbo].[Casari_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'CasariDetaliat_tru')
	DROP TRIGGER [dbo].[CasariDetaliat_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'CheltuieliVenitAvans_tru')
	DROP TRIGGER [dbo].[CheltuieliVenitAvans_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'CheltuieliVenitAvans_tri')
	DROP TRIGGER [dbo].[CheltuieliVenitAvans_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'Comenzi_tru')
	DROP TRIGGER [ComenziTransport].[Comenzi_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Garantii_tru')
	DROP TRIGGER [ComenziTransport].[Garantii_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Masini_tru')
	DROP TRIGGER [ComenziTransport].[Masini_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'ParcAuto_tru')
	DROP TRIGGER [ComenziTransport].[ParcAuto_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Soferi_tru')
	DROP TRIGGER [ComenziTransport].[Soferi_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'articole_tri')
	DROP TRIGGER [dbo].[articole_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'BonuriConsum_tri')
	DROP TRIGGER [dbo].[BonuriConsum_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'BonuriConsum_tru')
	DROP TRIGGER [dbo].[BonuriConsum_tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'BonuriConsumDetaliat_tri')
	DROP TRIGGER [dbo].[BonuriConsumDetaliat_tri]
GO

CREATE TRIGGER [dbo].[BonuriConsumDetaliat_tri] ON [dbo].[BonuriConsumDetaliat]
	WITH EXECUTE AS CALLER
	FOR INSERT
	AS
	BEGIN
		UPDATE FIRME..Soc SET Id_Numar = Id_Numar + 1 WHERE NumeDB = Db_Name()
		DECLARE @idUnic Int
		SET @IdUnic = (SELECT Id_Numar FROM Firme..Soc WHERE NumeDB = Db_Name())
		UPDATE BonuriConsumDetaliat SET IdUnic = @IdUnic WHERE ISNULL(IdUnic,0) = 0
	END
GO

If Exists ( Select * From sys.triggers Where Name = 'BonuriConsumDetaliat_tri2')
	DROP TRIGGER [dbo].[BonuriConsumDetaliat_tri2]
GO

If Exists ( Select * From sys.triggers Where Name = 'Casari_tri')
	DROP TRIGGER [dbo].[Casari_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'CasariDetaliat_tri')
	DROP TRIGGER [dbo].[CasariDetaliat_tri]
GO

CREATE TRIGGER [dbo].[CasariDetaliat_tri] ON [dbo].[CasariDetaliat]
	WITH EXECUTE AS CALLER
	FOR INSERT
	AS
	BEGIN
		UPDATE FIRME..Soc SET Id_Numar = Id_Numar + 1 WHERE NumeDB = Db_Name()
		DECLARE @idUnic Int
		SET @IdUnic = (SELECT Id_Numar FROM Firme..Soc WHERE NumeDB = Db_Name())
		UPDATE CasariDetaliat SET IdUnic = @IdUnic WHERE ISNULL(IdUnic,0) = 0
	END
GO

If Exists ( Select * From sys.triggers Where Name = 'CasariDetaliat_tri2')
	DROP TRIGGER [dbo].[CasariDetaliat_tri2]
GO

If Exists ( Select * From sys.triggers Where Name = 'conturi_tri2')
	DROP TRIGGER [dbo].[conturi_tri2]
GO

If Exists ( Select * From sys.triggers Where Name = 'intrari_tri')
	DROP TRIGGER [dbo].[intrari_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'Inventar_tri')
	DROP TRIGGER [dbo].[Inventar_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'NotePredare_tri')
	DROP TRIGGER [dbo].[NotePredare_tri]
GO

If Exists ( Select * From sys.triggers Where Name = 'NotePredareDetaliat_tri')
	DROP TRIGGER [dbo].[NotePredareDetaliat_tri]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='tipuriarticole')
	EXEC sp_rename '[dbo].[tipuriarticole]', 'TipuriArticole', 'OBJECT'
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='tipuriarticole')
	TRUNCATE TABLE [dbo].[TipuriArticole]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='tipuriarticole')
	/* Data for the 'dbo.TipuriArticole' table  (Records 1 - 16) */
	SET IDENTITY_INSERT [dbo].[TipuriArticole] ON
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (1, N'Marfuri', N'371', N'378', N'4428', N'607', N'707', 1, 0, 1, 0, 1, 0, 0)
	GO

	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (2, N'Materii prime', N'301', N'308', N'', N'601', N'', 1, 1, 0, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (3, N'Materiale auxiliare', N'3021', N'', N'', N'6021', N'', 1, 1, 0, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (4, N'Combustibili', N'3022', N'', N'', N'6022', N'', 1, 1, 0, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (5, N'Piese de schimb', N'3024', N'', N'', N'6024', N'', 1, 1, 0, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (6, N'Alte mat. consumabile', N'3028', N'', N'', N'6028', N'', 1, 1, 0, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (7, N'Produse finite', N'345', N'348', N'', N'711', N'701', 0, 0, 1, 1, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (8, N'Ambalaje', N'381', N'388', N'', N'608', N'708', 1, 0, 1, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (9, N'Obiecte de inventar', N'303', N'', N'', N'603', N'', 1, 0, 0, 0, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (10, N'Semifabricate', N'341', N'348', N'', N'711', N'702', 0, 1, 1, 1, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (11, N'Produse reziduale', N'346', N'348', N'', N'711', N'703', 0, 0, 1, 1, 1, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (12, N'Amenajari Proprii', N'323', N'', N'', N'603', N'', 1, 0, 0, 0, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (13, N'Mijloace Fixe', N'212', NULL, NULL, N'681', NULL, 1, 0, 0, 0, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (14, N'Discount Financiar Intrari', N'767', N'', N'', N'', N'', 1, 0, 0, 0, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (15, N'Discount Financiar Iesiri', N'667', N'', N'', N'', N'', 0, 0, 1, 0, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (16, N'Discount Comercial Intrari', N'609', N'', N'', N'', N'', 1, 0, 0, 0, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (17, N'Discount Comerical Iesiri', N'709', N'', N'', N'', N'', 0, 0, 1, 0, 0, 0, 0)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (18, N'Ven din SERVICII Vandute', N'704', N'', N'', N'', N'704', 0, 0, 1, 0, 0, 0, 1)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (19, N'Ch cu SERVICII Executate de TERTI', N'628', N'', N'', N'628', N'', 1, 0, 0, 0, 0, 0, 1)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (20, N'Mat. spre prelucrare', N'8032', N'', N'', N'999', N'', 1, 0, 0, 0, 0, 0, 1)
	GO

	
	INSERT INTO [dbo].[TipuriArticole] ([Id], [Denumire], [Cont], [Diferente], [Cont4428], [ContChelt], [ContVenit], [Aproviz], [Consumabil], [Vandabil], [ProdFinit], [Stocabil], [blocat], [Sters])
	VALUES (21, N'Mat. în pastrare/consig.', N'8033', N'', N'999', N'', N'', 1, 0, 0, 0, 0, 0, 1)
	GO

	
	SET IDENTITY_INSERT [dbo].[TipuriArticole] OFF		
	GO

IF EXISTS(SELECT * FROM sys.views WHERE name = 'ComboGestiune' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.ComboGestiune
GO

CREATE VIEW ComboGestiune AS 
	SELECT 
		'' AS DenGest,
		'' AS ContGest,
		'' AS ContVGest,
		0 AS IdGest,
		Cast(1 AS BIT) AS Aproviz,
		Cast(1 AS BIT) AS Vandabil,
		0 As IdTipArt,
		'' AS DenTipArt
	FROM Gestiuni 
	UNION 
	SELECT 
		g.Denumire AS DenGest,
		g.Cont AS ContGest,
		g.Glob_707 AS ContVGest,
		g.Id AS IdGest,
		Aproviz,
		Vandabil,
		Ta.Id AS IdTipArt,
		Ta.Denumire AS DenTipArt
	FROM Gestiuni g 
		INNER JOIN TipuriArticole ta ON LEFT(ta.CONT,3)=LEFT(g.CONT,3)
	WHERE Vandabil = 1
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Inchideri' AND COLUMN_NAME='Inch_Sal')
	ALTER TABLE [dbo].[Inchideri] ADD [Inch_Sal] bit NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Inchideri' AND COLUMN_NAME='Id_Sal')
	ALTER TABLE [dbo].[Inchideri] ADD [Id_Sal] int NULL
GO

IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='ParcAuto' AND COLUMN_NAME='IdVehicol')
	ALTER TABLE [ComenziTransport].[ParcAuto] ALTER COLUMN [IdVehicol] int
GO

IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='ParcAuto' AND COLUMN_NAME='NumarVehicol')
	ALTER TABLE [ComenziTransport].[ParcAuto] ALTER COLUMN [NumarVehicol] varchar(10) COLLATE Latin1_General_CI_AS
GO

IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Garantii' AND COLUMN_NAME='IdSofer')
	ALTER TABLE [ComenziTransport].[Garantii] ALTER COLUMN [IdSofer] int
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Retete' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE [dbo].[Retete] ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='PreturiAmanunt' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE [dbo].[PreturiAmanunt] ADD [iUserWorking] int NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='PreturiAmanunt' AND COLUMN_NAME='Validat')
	ALTER TABLE [dbo].[PreturiAmanunt] ALTER COLUMN [Validat] char(1) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Transferuri' AND COLUMN_NAME='IsGlobalValorica' AND COLUMN_DEFAULT IS NULL)
	ALTER TABLE [dbo].[Transferuri] ADD DEFAULT 0 FOR [IsGlobalValorica]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Transferuri' AND COLUMN_NAME='IdGest1')
	ALTER TABLE [dbo].[Transferuri] ALTER COLUMN [IdGest1] int
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='SoferSecundar')
	ALTER TABLE [ComenziTransport].[Comenzi] ADD [SoferSecundar] varchar(30) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='TransferuriDetaliat' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE [dbo].[TransferuriDetaliat] ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='NotePredareDetaliat' AND COLUMN_NAME='IdGest')
	ALTER TABLE [dbo].[NotePredareDetaliat] ADD [IdGest] int 
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='registru' AND COLUMN_NAME='RV')
	ALTER TABLE [dbo].[registru] DROP COLUMN [RV]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='Is_Tva')
	ALTER TABLE [dbo].[Conturi] ADD [Is_Tva] bit DEFAULT 1 NULL
GO

IF Not EXISTS ( SELECT t.name AS [Table Name], ex.value AS Description 
				FROM sys.tables AS t, sys.extended_properties AS ex
				WHERE 
					ex.major_id = t.object_id 
					AND ex.name = 'MS_Description' 
					AND t.Name = 'Conturi' 
					AND Value  = 'Daca firma este Platitoare de Tva')
	EXEC sp_AddExtendedProperty 'MS_Description', N'Daca firma este Platitoare de Tva', 'schema', 'dbo', 'table', 'conturi', 'column', 'Is_Tva'
GO

IF Object_id('Declaratii.D300') IS NULL
	CREATE TABLE [Declaratii].[D300] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Luna] numeric(2, 0) NULL,
	  [An] numeric(4, 0) NULL,
	  [Cont] char(4) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Rand] char(6) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Denumire] char(250) COLLATE Latin1_General_CI_AS NOT NULL,
	  [Valoare] numeric(15, 2) NULL,
	  [Tva] numeric(15, 2) NULL,
	  [Is_Col1] bit NOT NULL,
	  [Is_Col2] bit NOT NULL
	)
	ON [PRIMARY]
GO

ALTER TABLE [Declaratii].[D300] ALTER COLUMN [Cont] char(4) COLLATE Latin1_General_CI_AS
GO

IF Object_id('Declaratii.D390') IS NULL
	CREATE TABLE [Declaratii].[D390] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Luna] numeric(2, 0) NULL,
	  [An] numeric(4, 0) NULL,
	  [Nr_Crt] numeric(6, 0) NULL,
	  [Cod_Fiscal] char(24) COLLATE Latin1_General_CI_AS NULL,
	  [Cod] char(20) COLLATE Latin1_General_CI_AS NULL,
	  [Denumire] char(50) COLLATE Latin1_General_CI_AS NULL,
	  [Tara] char(2) COLLATE Latin1_General_CI_AS NULL,
	  [Baza_a] numeric(15, 0) NULL,
	  [Baza_l] numeric(15, 0) NULL,
	  [Baza_t] numeric(15, 0) NULL,
	  [Baza_s] numeric(15, 0) NULL,
	  [Baza_p] numeric(15, 0) NULL
	)
	ON [PRIMARY]
GO

IF Object_id('Declaratii.D394_Cumparari') IS NULL
	BEGIN 
		CREATE TABLE [Declaratii].[D394_Cumparari] (
		  [Id] int IDENTITY(1, 1) NOT NULL,
		  [Luna] numeric(2, 0) NULL,
		  [An] numeric(4, 0) NULL,
		  [Tip_T] char(1) COLLATE Latin1_General_CI_AS NULL,
		  [Cod_Tert] char(20) COLLATE Latin1_General_CI_AS NULL,
		  [Data] date NULL,
		  [Nr] char(16) COLLATE Latin1_General_CI_AS NULL,
		  [Total] numeric(15, 2) NULL,
		  [Baza_Tva] numeric(15, 2) NULL,
		  [Tva] numeric(15, 2) NULL,
		  [ok] bit NOT NULL
		)
		ON [PRIMARY]
	END
GO

IF Object_id('Declaratii.D394_Vanzari') IS NULL
	CREATE TABLE [Declaratii].[D394_Vanzari] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Luna] numeric(2, 0) NULL,
	  [An] numeric(4, 0) NULL,
	  [Tip_T] char(1) COLLATE Latin1_General_CI_AS NULL,
	  [Cod_Tert] char(20) COLLATE Latin1_General_CI_AS NULL,
	  [Data] date NULL,
	  [Nr] char(16) COLLATE Latin1_General_CI_AS NULL,
	  [Total] numeric(15, 2) NULL,
	  [Baza_Tva] numeric(15, 2) NULL,
	  [Tva] numeric(15, 2) NULL,
	  [ok] bit NOT NULL
	)
	ON [PRIMARY]
GO

IF Object_id('Declaratii.D394') IS NULL
	CREATE TABLE [Declaratii].[D394] (
	  [Id] int IDENTITY(1, 1) NOT NULL,
	  [Luna] numeric(2, 0) NULL,
	  [An] numeric(4, 0) NULL,
	  [Tip_T] char(1) COLLATE Latin1_General_CI_AS NULL,
	  [Cod_Tert] char(20) COLLATE Latin1_General_CI_AS NULL,  
	  [Denumire] char(50) COLLATE Latin1_General_CI_AS NULL,  
	  [Prefix] char(2) COLLATE Latin1_General_CI_AS NULL,  
	  [Cod_Fisc] char(24) COLLATE Latin1_General_CI_AS NULL,
	  [Is_Valid] bit NOT NULL,
	  [ok] bit NOT NULL,  
	  [Is_Tva] bit NOT NULL
	)
	ON [PRIMARY]
GO

If Exists ( Select * From sys.triggers Where Name = 'articole_trd2' )
	Drop Trigger [dbo].[articole_trd2]
GO

If Object_id('dbo.Comenzi') Is Not Null
	EXEC sp_rename '[dbo].[Comenzi]', 'ComenziAntet', 'OBJECT'
GO

If Exists ( Select * From sys.triggers Where Name = 'articole_trd' )
	Drop Trigger [dbo].[articole_trd]
GO

Create Trigger [dbo].[articole_trd] On [dbo].[articole]
	With Execute As Caller
	For Delete
	As
	Begin
		Declare @Error bit = 0
		Declare @Count int;
		Set @Count = @@RowCount;
		If @Count = 0 RETURN;
		Set NoCount On;
		Begin Try
			Declare @DenArticol VarChar(50) = (Select LTrim(Denumire) From deleted) 
			Declare @msg varchar(500) 
			Set @msg = 'Articolul [ ' +  LTrim(RTrim(@DenArticol)) + ' ] nu poate fi STERS deaoarece a fost folosit in :' + Char(13)
			/*** 1.  Articolul sa nu fie folosit In Intrari  ***/
			If Exists (	Select 	1 From deleted Inner Join IntrariDetaliat On IntrariDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Facturi de Intrare' + Char(13)
			End
			/*** 2.  Articolul sa nu fie folosit In Importuri  ***/
			If Exists (	Select 	1 From deleted Inner Join ImportDetaliat On ImportDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Facturi de Import' + Char(13)
			End
			/*** 3.  Articolul sa nu fie folosit In Iesiri  ***/
			If Exists (	Select 	1 From deleted Inner Join IesiriDetaliat On IesiriDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Facturi de Iesiri' + Char(13)
			End
			/*** 4.  Articolul sa nu fie folosit In Exporturi  ***/
			If Exists (	Select 	1 From deleted Inner Join ExportDetaliat On ExportDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Facturi de Export' + Char(13)
			End
			/*** 5.  Articolul sa nu fie folosit In Note de Predare  ***/
			If Exists (	Select 	1 From deleted Inner Join NotePredareDetaliat On NotePredareDetaliat.IdProdFin = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Note de Predare' + Char(13)
			End
			/*** 6.  Articolul sa nu fie folosit In Bonuri Consum   ***/
			If Exists (	Select 	1 From deleted Inner Join BonuriConsumDetaliat On BonuriConsumDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Bonuri Consum' + Char(13)
			End
			/*** 7.  Articolul sa nu fie folosit In Retete  ***/
			If Exists (	Select 	1 From deleted Inner Join Retete On Retete.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Retete' + Char(13)
			End
			/*** 8.  Articolul sa nu fie folosit In Transferuri intre Gestiuni   ***/
			If Exists (	Select 	1 From deleted Inner Join TransferuriDetaliat On TransferuriDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Transferuri intre Gestiuni' + Char(13)
			End
			/*** 9.  Articolul sa nu fie folosit In Reglari Stocuri   ***/
			If Exists (	Select 	1 From deleted Inner Join Reglari On Reglari.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Reglari' + Char(13)
			End
			/*** 10.  Articolul sa nu fie folosit In Casari Obiecte Inventar   ***/        
			If Exists (	Select 	1 From deleted Inner Join CasariDetaliat On CasariDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Casari Obiecte Inventar' + Char(13)
			End
			/*** 11.  Articolul sa nu fie folosit In Comenzi (AI GRIJA SA MODIfICI AICI DACA SCHIMBI NUMELE TABELEI!!!) ***/        
			If Exists (	Select 	1 From deleted Inner Join ComenziAntet On ComenziAntet.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-ComenziAntet' + Char(13)
			End
			/*** 12.  Articolul sa nu fie folosit In ComenziDetaliat   ***/
			If Exists (	Select 	1 From deleted Inner Join ComenziDetaliat On ComenziDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Detalii Comenzi' + Char(13)
			End
			/*** 13.  Articolul sa nu fie folosit In Inventar   ***/
			If Exists (	Select 	1 From deleted Inner Join InventarDetaliat On InventarDetaliat.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Inventar' + Char(13)
			End
			/*** 14.  Articolul sa nu fie folosit In Operatii Speciale   ***/
			If Exists (	Select 	1 From deleted Inner Join OperatiiSpeciale On OperatiiSpeciale.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Operatii Speciale' + Char(13)
			End
			/*** 15.  Articolul sa nu fie folosit In PreluareStocuri   ***/
			If Exists (	Select 	1 From deleted Inner Join PreluareStocuri On PreluareStocuri.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Preluare Stocuri' + Char(13)
			End
			/*** 16.  Articolul sa nu fie folosit In PreturiAmanunt   ***/
			If Exists (	Select 	1 From deleted Inner Join PreturiAmanunt On PreturiAmanunt.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Schimbare Preturi Amanunt' + Char(13)
			End
			/*** 17.  Articolul sa nu fie folosit In Serii   ***/
			If Exists (	Select 	1 From deleted Inner Join Serii On Serii.IdArticol = deleted.Id )
			Begin
				Set @Error = 1
				Set @msg = @msg + '-Serii' + Char(13)
			End
		End Try
		Begin Catch
			If @@TranCount > 0
			Begin
				RollBack Transaction;
			End
		End Catch;
		If @Error = 1
		Begin
			RaisError(@msg,10,1)
			If @@TranCount > 0
			Begin
				RollBack Transaction;
			End
	   End     
	End
GO

If Exists ( Select * From sys.triggers Where Name = 'gestiuni_trd2' )
	Drop Trigger [dbo].[gestiuni_trd2]
GO

If Exists ( Select * From sys.triggers Where Name = 'gestiuni_trd' )
	Drop Trigger [dbo].[gestiuni_trd]
GO

CREATE TRIGGER [dbo].[gestiuni_trd] ON [dbo].[gestiuni]
	WITH EXECUTE AS CALLER
	FOR DELETE
	AS
	BEGIN
		DECLARE @Count int;
		SET @Count = @@ROWCOUNT;
		IF @Count = 0 RETURN;
		SET NOCOUNT ON;
		
		BEGIN TRY

			DECLARE @DenGest VarChar(50) = (SELECT LTRIM(Denumire) FROM deleted) 
			DECLARE @msg VarChar(150) 

			/*** 1.  Gestiunea sa nu fie folosita In ExportDetaliat  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN ExportDetaliat ON ExportDetaliat.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Export pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			  END

			/*** 2.  Gestiunea sa nu fie folosita In Retete  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Retete ON Retete.Idgest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Retete pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 3.  Gestiunea sa nu fie folosita In ImportDetaliat  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN ImportDetaliat ON ImportDetaliat.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Import pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 4.  Gestiunea sa nu fie folosita In BonuriConsumDetaliat  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN BonuriConsumDetaliat ON BonuriConsumDetaliat.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Bonuri De Consum pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 5.  Gestiunea sa nu fie folosita In BonuriConsum  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN BonuriConsum ON BonuriConsum.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Bonuri De Consum pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 6.  Gestiunea sa nu fie folosita In Serii  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Serii ON Serii.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Serii pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 7.  Gestiunea sa nu fie folosita In ItemsDischarge   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN ItemsDischarge ON ItemsDischarge.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Descarcari pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 8.  Gestiunea sa nu fie folosita In Comenzi (AI GRIJA SA MODIFICI AICI DACA SCHIMBI NUMELE TABELEI!!!) ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN ComenziAntet ON ComenziAntet.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti ComenziAntet pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END
			
			/*** 9.  Gestiunea sa nu fie folosita In ComenziDetaliat  ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN ComenziDetaliat ON ComenziDetaliat.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Comenzi pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END
			
			/*** 10.  Gestiunea sa nu fie folosita In NotePredareDetaliat   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN NotePredareDetaliat ON NotePredareDetaliat.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Note Predare pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 11. Gestiuni sa nu fie folosita In Casari   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Casari ON Casari.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Casari pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 12.  Gestiunea sa nu fie folosita In IntrariDetaliat   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN IntrariDetaliat ON IntrariDetaliat.idGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Date Introduse in Intrari pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 13.  Gestiunea sa nu fie folosita In OperatiiSpeciale   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN OperatiiSpeciale ON OperatiiSpeciale.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Date Introduse in Operatii Speciale pe aceasta Gestiune! '+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 14.  Gestiunea sa nu fie folosita In Reglari   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Reglari ON Reglari.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Reglari de Stocuri pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 15.  Gestiunea sa nu fie folosita In PreluareStocuri   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN PreluareStocuri ON PreluareStocuri.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti preluari de stoc pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 16.  Gestiunea sa nu fie folosita In Inventar   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Inventar ON Inventar.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Inventar pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 17.  Gestiunea sa nu fie folosita In IesiriDetaliat   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN IesiriDetaliat ON IesiriDetaliat.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Iesiri pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 18.  Gestiunea sa nu fie folosita In Import   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Import ON Import.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Import pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 19.  Gestiunea sa nu fie folosita In Articole   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN Articole ON Articole.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti date introduse in Articole pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 20.  Gestiunea sa nu fie folosita In NotePredare   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN NotePredare ON NotePredare.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Note Predare pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END

			/*** 21.  Gestiunea sa nu fie folosita In Miscari   ***/
			IF EXISTS (	SELECT 	1 FROM deleted INNER JOIN ItemsTransactions ON ItemsTransactions.IdGest = deleted.Id )
			BEGIN
				SET @msg = 'Aveti Miscari pe aceasta Gestiune!'+CHAR(13) +SPACE(15)+ @Dengest 
				RAISERROR(@msg,16,0)
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END
			END
		END TRY
		BEGIN CATCH
			EXECUTE [dbo].[uspPrintError];
			-- Rollback any active or uncommittable transactions before inserting information in the ErrorLog
			IF @@TRANCOUNT > 0
			BEGIN
				ROLLBACK TRANSACTION;
			END

			EXECUTE [dbo].[uspLogError];
		END CATCH;
	END
GO

If EXISTS ( Select * From sys.triggers Where Name = 'Conturi_Trd' )
	Drop Trigger [dbo].[Conturi_Trd]
GO

If Exists ( Select * From sys.triggers Where Name = 'Conturi_Tru' )
	Drop Trigger [dbo].[Conturi_Tru]
GO

If Exists ( Select * From sys.triggers Where Name = 'Conturi_Tru2' )
	Drop Trigger [dbo].[Conturi_Tru2]
GO

Create Trigger  [dbo].[Conturi_Tru] On [dbo].[Conturi]
	With Execute As CALLER
	For Update
	As
Begin
        /* Trigger body */

    Declare @Count int;
    Set @Count = @@ROWCOUNT;
    If @Count = 0 
        Return;
    Set NoCount On;

    Begin Try
		-- Declare @UpdateId Int =	(Select Id From Deleted);
		-- Declare @Cont Char(20) = (Select Cont From Deleted); 
		-- Declare @ContTrim VarChar(20) = (Select Left(Cont, Len(Cont)) From Deleted); 

		/*** 20.  Contul  sa nu fie folosit In Registru DEBIT  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Registru tz On d.Cont=tz.ContD Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Note Contabile DEBIT pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 21.  Contul  sa nu fie folosit In Registru  CREDIT ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Registru tz On d.Cont=tz.ContC Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Note Contabile CREDIT pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End
		
		/*** 1.  Contul  sa nu fie folosit In Amortizari  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Amortizari a On d.Cont=a.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Amortizari pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 2.  Contul  sa nu fie folosit In CheltuieliVenitAvans  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join CheltuieliVenitAvans cva On d.Cont=cva.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Cheltuieli Venit pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 3.  Contul  sa nu fie folosit In ComenziTransport.Comenzi  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join ComenziTransport.Comenzi com  On d.Cont=com.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Comenzi Transport pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 4.  Contul  sa nu fie folosit In ComenziTerti  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join ComenziTerti ct On d.Cont=ct.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Comenzi terti pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 5.  Contul  sa nu fie folosit In Contracte  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Contracte ct  On d.Cont=ct.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Contracte Clienti pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 6.  Contul  sa nu fie folosit In Export  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Export e On d.Cont=e.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Export pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 7.  Contul  sa nu fie folosit In ExportDetaliat  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join ExportDetaliat ed On d.Cont=ed.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Export Detaliat pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 8.  Contul  sa nu fie folosit In Gestiuni  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Gestiuni g On d.Cont=g.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Gestiuni pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End
		  
		/*** 9.  Contul  sa nu fie folosit In Iesiri  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Iesiri ie On d.Cont=ie.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Iesiri pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 10.  Contul  sa nu fie folosit In IesiriDetaliat  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join IesiriDetaliat id On d.Cont=id.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Iesiri pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 11.  Contul  sa nu fie folosit In Import  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Import On d.Cont=Import.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Iesiri pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

			  
		/*** 12.  Contul  sa nu fie folosit In ImportDetaliat  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join ImportDetaliat im On d.Cont=im.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Import pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 13.  Contul  sa nu fie folosit In ImportTransport  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join ImportTransport it On d.Cont=it.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Import Transport pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 14.  Contul  sa nu fie folosit In InchideriCheltuieliVenituri  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join InchideriCheltuieliVenituri icv On d.Cont=icv.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Inchideri Cheltuieli pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 15.  Contul  sa nu fie folosit In Intrari  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join Intrari On d.Cont=intrari.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Intrari pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End


		/*** 16.  Contul  sa nu fie folosit In IntrariDetaliat  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join IntrariDetaliat id On d.Cont=id.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Intrari pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End
			  
		/*** 17.  Contul  sa nu fie folosit In MijloaceFixe  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join MijloaceFixe mj On d.Cont=mj.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Mijloace Fixe pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 18.  Contul  sa nu fie folosit In OperatiiSpeciale  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join OperatiiSpeciale os On d.Cont=os.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in Operatii Speciale pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End

		/*** 19.  Contul  sa nu fie folosit In TipuriArticole  ***/
		If Exists(Select 1 From deleted d Inner Join Inserted i On d.Id = i.Id Inner Join TipuriArticole ta On d.Cont=ta.Cont Where d.Sters<>i.Sters Or d.Cont <> i.Cont)
		Begin
			RaisError('Aveti date introduse in TipuriArticole pe acest Cont!',16,0)
			Rollback Transaction
			Return
		End


    End Try

    Begin Catch
        Execute [dbo].[uspPrintError];
        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        If @@TranCount > 0
        Begin
            RollBack Transaction;
        End
        Execute [dbo].[uspLogError];
    End Catch;

End
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='LunaAnul' AND COLUMN_NAME='Val_Casate')
	ALTER TABLE [dbo].[LunaAnul] ADD [Val_Casate] numeric(14, 2) NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='Telefon')
	ALTER TABLE [dbo].[conturi] ALTER COLUMN [telefon] char(50) COLLATE Latin1_General_CI_AS
GO

IF Object_id('dbo.Loturi') IS NULL
	CREATE TABLE [dbo].[Loturi] (
	[Id] int IDENTITY(1, 1) NOT NULL,
	[Denumire] char(50) NULL,
	[Producator] char(50) NULL,
	[DataFabricarii] date NULL,
	[DataExpirarii] date NULL,
	[Observatii] char(254) NULL,
	PRIMARY KEY CLUSTERED ([Id])
	)
GO

IF Not EXISTS ( SELECT t.name AS [Table Name], ex.value AS Description 
				FROM sys.tables AS t, sys.extended_properties AS ex
				WHERE 
					ex.major_id = t.object_id 
					AND ex.name = 'MS_Description' 
					AND t.Name = 'Loturi' 
					AND Value  = 'Denumire Lot')
	EXEC sp_addextendedproperty 'MS_Description', N'Denumire Lot', 'schema', 'dbo', 'table', 'Loturi', 'column', 'Denumire'
GO

IF Not EXISTS ( SELECT t.name AS [Table Name], ex.value AS Description 
				FROM sys.tables AS t, sys.extended_properties AS ex
				WHERE 
					ex.major_id = t.object_id 
					AND ex.name = 'MS_Description' 
					AND t.Name = 'Loturi' 
					AND Value  = 'Producatorul Lotului')

	EXEC sp_addextendedproperty 'MS_Description', N'Producatorul Lotului', 'schema', 'dbo', 'table', 'Loturi', 'column', 'Producator'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Loturi' AND COLUMN_NAME='iUserWorking')
	ALTER TABLE [dbo].[Loturi] ADD [iUserWorking] int NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Loturi' AND COLUMN_NAME='CreatedBy')
	ALTER TABLE [dbo].[Loturi] ADD [CreatedBy] nvarchar(128) NULL
GO

If Exists ( Select * From sys.triggers Where Name = 'loturi_trd' )
	Drop Trigger [dbo].[loturi_trd]
GO

CREATE TRIGGER [dbo].[loturi_trd] ON [dbo].[Loturi]
	WITH EXECUTE AS CALLER
	FOR DELETE
	AS
	BEGIN
		Declare @Error bit = 0
		DECLARE @Count int;
		SET @Count = @@ROWCOUNT;
		IF @Count = 0 RETURN;
		SET NOCOUNT ON;

		BEGIN TRY
			DECLARE @DenLot varchar(50) = (SELECT LTRIM(Denumire) FROM deleted) 
			DECLARE @msg varchar(150) 
			SET @msg = 'Lotul [ ' +  LTRIM(RTRIM(@DenLot)) + ' ] nu poate fi STERS deaoarece a fost folosit in :' + Char(13)
			
			--*** 1.  Lotul sa nu fie folosit In Intrari  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN IntrariDetaliat ON IntrariDetaliat.IdLot = deleted.Id)
			BEGIN
				SET @Error = 1
				SET @msg = @msg + '-Facturi de Intrare' + Char(13)
			END
		
			-- *** 2.  Lotul sa nu fie folosit In Import  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN ImportDetaliat ON ImportDetaliat.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Facturi de Import' + Char(13)
			  END

			--*** 3.  Lotul  sa nu fie folosit In Iesiri  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN IesiriDetaliat ON IesiriDetaliat.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Facturi de Iesire' + Char(13)
			  END

			--*** 4.  Lotul sa nu fie folosit In Export  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN ExportDetaliat ON ExportDetaliat.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Facturi de Export' + Char(13)
			  END

			--*** 5.  Lotul sa nu fie folosit In Bonuri Consum  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN BonuriConsumDetaliat ON BonuriConsumDetaliat.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Bonuri de Consum' + Char(13)
			  END
			  
			--*** 6.  Lotul sa nu fie folosit In Descarcari  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN ItemsDischarge ON ItemsDischarge.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Descarcari' + Char(13)
			  END
			  
			--*** 7.  Lotul sa nu fie folosit In Note Predare Detaliat ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN NotePredareDetaliat ON NotePredareDetaliat.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Note Predare' + Char(13)
			  END
			  
			--*** 8.  Lotul sa nu fie folosit In ItemsTransactions  ***
			IF EXISTS (SELECT 1 FROM deleted INNER JOIN ItemsTransactions ON ItemsTransactions.IdLot = deleted.Id)
			  BEGIN
					SET @Error = 1
					SET @msg = @msg + '-Miscari' + Char(13)
			  END
			  IF @Error = 1
			  BEGIN
				  RAISERROR(@msg,10,1)
				  IF @@TRANCOUNT > 0
				  BEGIN
					  ROLLBACK TRANSACTION;
				  END
			 END     
		END TRY
		BEGIN CATCH
			IF @@TRANCOUNT > 0
			BEGIN
				ROLLBACK TRANSACTION;
			END
		END CATCH;
	END
GO

IF EXISTS(SELECT * FROM sys.views WHERE name = 'ArticoleFactura' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.ArticoleFactura
GO

IF EXISTS(SELECT * FROM sys.views WHERE name = 'vArticoleFactura' AND schema_id = SCHEMA_ID('dbo'))
	DROP VIEW dbo.vArticoleFactura
GO

Create View vArticoleFactura As 
Select
	a.Denumire As Articol,
	a.Um As Um,
	g.Cont As Cont,   
	g.Id As IdGest,
	g.Denumire As DenGest,
	IsNull(Stocabil,0) As Stocabil,     
	a.Pret_Vanz, 
	a.Pret_Aman As PretAmanunt, 
	a.Id As Id,    
	a.Tva As ProcTva, 
	ta.Denumire As DenTipArt, 
	ta.Id As IdTipArt, 
	0 As IdMf,
	a.IsLot
From Gestiuni g
	Left Join TipuriArticole ta  On g.IdTipArt = ta.Id
	Inner Join Articole a On a.IdTipArt = ta.Id    
	Where
		ta.Aproviz = 1 
		And Stocabil = 1 
		And IsNull(ta.Sters, 0) = 0 
		And g.Tip_Gest = 'Cantitativ-Valorica'
Union
Select
	'Marfuri' As Articol,
	'Buc' As Um,
	g.Cont As Cont,   
	g.Id As IdGest,
	g.Denumire As DenGest,
	IsNull(Stocabil, 0) As Stocabil,     
	0 As Pret_Vanz, 
	0 As PretAmanunt, 
	Null As Id,    
	24 As ProcTva, 
	ta.Denumire As DenTipArt, 
	ta.Id As IdTipArt, 
	0 As IdMf,
	Cast(0 As Bit) As IsLot
From Gestiuni g
	Left Join TipuriArticole ta On g.IdTipArt = ta.Id
	Inner Join Articole a On a.IdTipArt = ta.Id    
	Where
		ta.Aproviz = 1 
		And Stocabil = 1 
		And IsNull(ta.sters,0) = 0
		And g.Tip_Gest <> 'Cantitativ-Valorica'
Group By g.Cont, g.Id, g.Denumire, ta.Stocabil, ta.Denumire, ta.id
Union
Select
   	ta1.Denumire As Articol, 
	'buc' As Um, 
	ta1.Cont As Cont, 
	Null As IdGest, 
	Null As DenGest, 
	IsNull(ta1.Stocabil, Convert(bit, 0)) As Stocabil, 
	0 As Pret_Vanz, 
	0 As PretAmanunt, 
	0 As Id, 
	0 As ProcTva, 
	IsNull(ta1.Denumire, 'Cheltuieli') As DenTipArt, 
	IsNull(ta1.Id, 0) As IdTipArt, 
	0 As IdMf,
	Cast(0 As Bit) As IsLot
From TipuriArticole ta1  
	Inner Join Conturi c On c.Cont = ta1.Cont
	Where 
		ta1.Aproviz = 1 
		And Stocabil = 0  
		And IsNull(ta1.Sters, 0) = 0
Union
Select
   	mf.Denumire As Articol, 
	'buc' As Um, 
	mf.Cont As Cont, 
	Null As IdGest, 
	Null As DenGest, 
	Convert(bit, 0) As Stocabil, 
	0 As Pret_Vanz, 
	0 As PretAmanunt, 
	0 As Id, 
	0 As ProcTva, 
	IsNull(mf.Denumire, 'Mijloace Fixe') As DenTipArt,
	13 As IdTipArt, 
	mf.Id As IdMf, 
	Cast(0 As Bit) As IsLot
From MijloaceFixe mf

	/*
	SELECT a.Denumire AS Articol,a.Um, g.CONT , g.id AS IDGest, g.denumire AS DenGest, 
	ta.Stocabil, a.Pret_Vanz, a.Pret_Aman AS PretAmanunt, a.Id , a.Tva As ProcTva, 
	ta.Denumire As DenTipArt, ta.Id As IdTipArt, 0 As IdMf
	FROM articole a
	inner join ArtGest ag ON ag.IdArticol = a.id
	INNER JOIN gestiuni g ON g.id = ag.idgestiune
	INNER JOIN tipuriarticole ta ON LEFT(ta.CONT,3)=LEFT(g.CONT,3) 
	WHERE ta.Aproviz = 1 AND Stocabil = 1 AND ISNULL(ta.sters,0) = 0
	*/
GO

If Exists ( Select * From sys.triggers Where Name = 'IntrariDetaliat_tri' )
	Drop Trigger [dbo].[IntrariDetaliat_tri]
GO

Create Trigger [dbo].[IntrariDetaliat_tri] ON [dbo].[IntrariDetaliat]
With Execute As CALLER
For Insert
As
Set NoCount On 
Set ArithAbort On 
Begin
	If Exists(Select IdUnic From Inserted Where IsNull(IdUnic, 0) = 0)
	Begin
		Update Firme..Soc Set Id_Numar = Id_Numar + 1 Where NumeDB = Db_Name()
		Declare @IdUnic Int
		Set @IdUnic = (Select Id_Numar From Firme..Soc Where NumeDB = Db_Name())
		Update IntrariDetaliat Set IdUnic = @IdUnic Where IsNull(IdUnic, 0) = 0
	End
End
GO


If Exists ( Select * From sys.triggers Where Name = 'IesiriDetaliat_tri' )
	Drop Trigger [dbo].[IesiriDetaliat_tri]
GO


Create Trigger [dbo].[IesiriDetaliat_tri] ON [dbo].[IesiriDetaliat]
With Execute As CALLER
For Insert
As
Set NoCount On 
Set ArithAbort On 
Begin
	If Exists(Select IdUnic From Inserted Where IsNull(IdUnic, 0) = 0)
	Begin
		Update Firme..Soc Set Id_Numar = Id_Numar + 1 Where NumeDB = Db_Name()
		Declare @IdUnic Int
		Set @IdUnic = (Select Id_Numar From Firme..Soc Where NumeDB = Db_Name())
		Update IesiriDetaliat Set IdUnic = @IdUnic Where IsNull(IdUnic, 0) = 0
	End
End
GO


If Exists ( Select * From sys.triggers Where Name = 'ImportDetaliat_tri' )
	Drop Trigger [dbo].[ImportDetaliat_tri]
GO


Create Trigger [dbo].[ImportDetaliat_tri] ON [dbo].[ImportDetaliat]
With Execute As CALLER
For Insert
As
Set NoCount On 
Set ArithAbort On 
Begin
	If Exists(Select IdUnic From Inserted Where IsNull(IdUnic, 0) = 0)
	Begin
		Update Firme..Soc Set Id_Numar = Id_Numar + 1 Where NumeDB = Db_Name()
		Declare @IdUnic Int
		Set @IdUnic = (Select Id_Numar From Firme..Soc Where NumeDB = Db_Name())
		Update ImportDetaliat Set IdUnic = @IdUnic Where IsNull(IdUnic, 0) = 0
	End
End
GO


If Exists ( Select * From sys.triggers Where Name = 'ExportDetaliat_tri' )
	Drop Trigger [dbo].[ExportDetaliat_tri]
GO


Create Trigger [dbo].[ExportDetaliat_tri] ON [dbo].[ExportDetaliat]
With Execute As CALLER
For Insert
As
Set NoCount On 
Set ArithAbort On 
Begin
	If Exists(Select IdUnic From Inserted Where IsNull(IdUnic, 0) = 0)
	Begin
		Update Firme..Soc Set Id_Numar = Id_Numar + 1 Where NumeDB = Db_Name()
		Declare @IdUnic Int
		Set @IdUnic = (Select Id_Numar From Firme..Soc Where NumeDB = Db_Name())
		Update ExportDetaliat Set IdUnic = @IdUnic Where IsNull(IdUnic, 0) = 0
	End
End
GO


If Not Exists (SELECT 1 FROM Configurari.SystemParameters WHERE sKey = 'PersFact_Nume')
	INSERT INTO [Configurari].[SystemParameters] ([sKey], [sDescription], [sValue], [sDefaultValue], [iUserWorking], [Blocat], [modul], [AcceptValue], [IsHidden], [IsReadOnly])
	VALUES (N'PersFact_Nume', N'Nume si Prenume Persoana Facturare', N'', N'', NULL, 1, NULL, NULL, 0, 0)
GO


If Not Exists (SELECT 1 FROM Configurari.SystemParameters WHERE sKey = 'PersFact_CI')
	INSERT INTO [Configurari].[SystemParameters] ([sKey], [sDescription], [sValue], [sDefaultValue], [iUserWorking], [Blocat], [modul], [AcceptValue], [IsHidden], [IsReadOnly])
	VALUES (N'PersFact_CI', N'Ci / BI Persoana Facturare', N'', N'', NULL, 1, NULL, NULL, 0, 0)
GO


If Not Exists (SELECT 1 FROM Configurari.SystemParameters WHERE sKey = 'PersFact_Cnp')
	INSERT INTO [Configurari].[SystemParameters] ([sKey], [sDescription], [sValue], [sDefaultValue], [iUserWorking], [Blocat], [modul], [AcceptValue], [IsHidden], [IsReadOnly])
	VALUES (N'PersFact_Cnp', N'CNP Persoana Facturare', N'', N'', NULL, 1, NULL, NULL, 0, 0)
GO


IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='ParcAuto' AND COLUMN_NAME='LicentaTransportDataInceput')
	ALTER TABLE [ComenziTransport].[ParcAuto] ADD [LicentaTransportDataInceput] date NULL
GO


IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='ParcAuto' AND COLUMN_NAME='LicentaTransportDataSfarsit')
	ALTER TABLE [ComenziTransport].[ParcAuto] ADD [LicentaTransportDataSfarsit] date NULL
GO


IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='Cont_Vechi')
	ALTER TABLE [dbo].[Conturi] ADD [Cont_Vechi] char(20) NULL
GO


IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Conturi' AND COLUMN_NAME='Cont_Nou')
	ALTER TABLE [dbo].[Conturi] ADD [Cont_Nou] char(20) NULL
GO


IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='Comenzi' AND COLUMN_NAME='IsUpdated')
	ALTER TABLE [ComenziTransport].[Comenzi] ADD [IsUpdated] bit DEFAULT 0 NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Registru' AND COLUMN_NAME='IsUpdated')
	ALTER TABLE [dbo].[Registru] ADD [IsUpdated] bit DEFAULT 0 NULL
GO

DROP INDEX [registru_cont_d] ON [dbo].[registru]
GO

ALTER TABLE [dbo].[registru]
ALTER COLUMN [Cont_D] char(20) COLLATE Latin1_General_CI_AS
GO

CREATE NONCLUSTERED INDEX [registru_cont_d] ON [dbo].[registru]
  ([Cont_D], [Data])
WITH (
  PAD_INDEX = OFF,
  DROP_EXISTING = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO

DROP INDEX [registru_cont_c] ON [dbo].[registru]
GO

ALTER TABLE [dbo].[registru]
ALTER COLUMN [Cont_C] char(20) COLLATE Latin1_General_CI_AS
GO

CREATE NONCLUSTERED INDEX [registru_cont_c] ON [dbo].[registru]
  ([Cont_C], [Data])
WITH (
  PAD_INDEX = OFF,
  DROP_EXISTING = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Export' AND COLUMN_NAME='IsUpdated')
	ALTER TABLE [dbo].[Export] ADD [IsUpdated] bit DEFAULT 0 NULL
GO

-- Install Audit
-- Exec pAuditAll

GO

If Exists(Select * From sysobjects Where name ='GetIdUnic')
  DROP Procedure [GetIdUnic]
GO

Create Procedure dbo.GetIdUnic
	@lValue int Output
As
/*
Exemplu de Utilizare
Declare @i int ;
Execute GetIdUnic @i Output
Select @i AS IdUnic     
*/
Begin
  Update Firme..Soc Set Id_Numar = IsNull(Id_Numar, 0) + 1 Where NumeDb = Db_Name()
  Select @lValue = Id_Numar	
  From Firme..Soc
  Where NumeDb = Db_Name()
End
GO

IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'Bilant')
	EXECUTE ('CREATE SCHEMA Bilant AUTHORIZATION dbo;')
GO

IF Object_id('Bilant.Corelatii') IS NULL
    CREATE TABLE [Bilant].[Corelatii] (
  [expresie1] char(50) COLLATE Latin1_General_CI_AS  NULL,
  [expresie2] char(80) COLLATE Latin1_General_CI_AS  NULL,
  [operator] char(2) COLLATE Latin1_General_CI_AS  NULL,
  [conditie] char(50) COLLATE Latin1_General_CI_AS  NULL,
  [proven1] char(6) COLLATE Latin1_General_CI_AS  NULL,
  [proven2] char(6) COLLATE Latin1_General_CI_AS  NULL,
  [coloana1] bit  NULL,
  [coloana2] bit  NULL,
  [ok] bit  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.corelatii' table  (Records 1 - 49) */

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r4', N'r1 + r2 + r3', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r9', N'r5 + r6 + r7 + r8', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r12', N'r9+r10-r11-r18', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r13', N'r4+r12', N'=', N'', N'Bilant', N'Bilant', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r16', N'r17 + r18', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r19', N'r20+r21+r22', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r22', N'0', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r34', N'r19 + r23 + r24 + r25 - r26 + r27 - r28  + r29 - r30 + r31 - r32 -r33', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r36', N'r34 + r35', N'=', N'', N'Bilant', N'Bilant', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r36', N'r13 - r14 - r15 - r17', N'=', N'', N'Bilant', N'Bilant', 1, 1, 1)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r19+r35', N'0', N'>=', N'', N'Bilant', N'Bilant', 1, 0, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r19+r35', N'0', N'>', N'', N'Bilant', N'Bilant', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r1', N'0', N'>=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r1', N'r2+r3+r4+r5', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r10', N'r2 +r3 + r4 + r5 +r6 - r7 + r8 + r9', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r15', N'r16 + r17', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r18', N'r19 - r20', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r21', N'r22 - r23', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r24', N'r25 + r26 + r27 + r28', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r29', N'r30 - r31', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r32', N'r11+r12+r13+ r14+r15+r18+r21+r24+r29', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r33', N'r10 - r32', N'=', N'r10 - r32>0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r34', N'r32 - r10', N'=', N'r10 - r32<=0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r35', N'r36', N'>=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r37', N'r38', N'>=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r39', N'r40', N'>=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r42', N'r35 + r37 + r39 + r41', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r43', N'r44 - r45', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r46', N'r47', N'>=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r49', N'r43 + r46 +r48', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r50', N'r42 - r49', N'=', N'r42-r49>0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r51', N'r49-r42', N'=', N'r42-r49<=0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r52', N'r10 + r42 - r32 - r49', N'=', N'r10+r42-r32-r49>0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r53', N'r32 + r49 - r10 - r42', N'=', N'r10+r42-r32-r49<=0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r56', N'r54 - r55', N'=', N'r53-r55>0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r57', N'r55 - r54', N'=', N'r53-r55<=0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r58', N'r10 + r42 + r54', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r59', N'r32 + r49 + r55', N'=', N'', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r60', N'r58  - r59', N'=', N'r58 -r59>0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r61', N'r59 - r58', N'=', N'r58 -r59<=0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r64', N'r60 - r61 - r62 - r63', N'=', N'r60-r61-r62-r63>0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r65', N'r61 + r62 + r63 - r60', N'=', N'r60-r61-r62-r63<=0', N'CPP', N'CPP', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r31', N'r64', N'=', N'', N'Bilant', N'CPP', 1, 1, 1)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r32', N'r65', N'=', N'', N'Bilant', N'CPP', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r31', N'r1', N'=', N'', N'Bilant', N'DI1', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r32', N'r2', N'=', N'', N'Bilant', N'DI1', 0, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r1', N'r4 - r15 - r25', N'=', N'', N'Bilant', N'AI', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r2', N'r10 - r20 - r31', N'=', N'', N'Bilant', N'AI', 1, 1, 0)
GO

INSERT INTO [Bilant].[corelatii] ([expresie1], [expresie2], [operator], [conditie], [proven1], [proven2], [coloana1], [coloana2], [ok])
VALUES (N'r3', N'r11 - r32', N'=', N'', N'Bilant', N'AI', 1, 1, 1)
GO

IF Object_id('Bilant.c_fb') IS NULL
    CREATE TABLE [Bilant].[c_fb] (
  [indicator] char(248) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] varchar(max) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fb' table  (Records 1 - 39) */

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'A. ACTIVE IMOBILIZATE', 0, N'')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'I. IMOBILIZARI NECORPORALE (ct.201+203+205+2071+208+233+234-280-290-2933)', 1, N'(201, d) + (203, d) + (205, d) + (2071, d) + (208, d) +(233,d) + (234,d) - (280, c) - (290, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'II. IMOBILIZARI CORPORALE (ct.211+212+213+214+231+232-281-291-2931)', 2, N'(211, d) + (212, d) + (213, d) + (214, d) + (231, d) + (232, d) - (281, c) - (291,c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'III. IMOBILIZARI FINANCIARE (ct.261+263+265+267*-296*)', 3, N'(261, d) + (263, d) + (265, d) - (296, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'                                 ACTIVE IMOBILIZATE - TOTAL (rd. 01+02+03)', 4, N'r1 + r2 + r3')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'B. ACTIVE CIRCULANTE', 0, N'')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'I. STOCURI (ct.301+302+303±308+331+332+341+345+346±348+351+354+356 +357+358+361± 368+371±378+381±388-391-392-393-394-395-396-397-398 +4091-4428)', 5, N'(301, d) + (302, d) + (303, d) + (308, d) + (331, d) + (332, d) + (341, c) + (345, d) + (346, d) + (348, d) + (351, d) + (354, d) + (356, d) + (357,d) + (358, d) + (361, d)  + (368, d) - (368, c) + (371,d) + (378,d)  + (381,d) + (388,d) - (391, c) - (392, c) - (393, c) - (394, c) - (395, c) - (396, c) - (397, c) - (398, c) + (4091,d) - (4428,c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'II. CREANTE 28) (ct.267*-296*+4092+411+413+418+425+4282+431+437+4382 +441+4424+4428+444+445+446+447+4482+451+453+456+4582+461 +473-491-495-496+5187)', 6, N'(267, d) - (296, c) +(4092, d) + (411, d) + (413, d) + (418, d) + (425, d) + (4282, d) + (431, d) + (437, d) + (4382, d) + (441, d) + (4424, d) + (4428, d) + (444, d) + (445, d) + (446, d) + (447, d) + (4482, d) + (451, d) + (456, d) + (4582, d) + (461, d) + (473, d) - (491, c) - (495, c) - (496, c) + (5187,d)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'III. INVESTITII PE TERMEN SCURT (ct.501+505+506+508+5113+5114-591-595-596-598)', 7, N'(501, d) + (505, d) + (506, d) + (508, d) + (5113,d) + (5114,d) - (591, c) - (595, c) - (596, c) - (598, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'IV. CASA SI CONTURI LA BANCI (ct. 5112+512+531+532+541+542)', 8, N'(5112, d) + (512, d) + (531, d) + (532, d) + (541, d) + (542, d)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'                                ACTIVE CIRCULANTE - TOTAL (rd.05+06+07+08)', 9, N'r5 + r6 + r7 + r8')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'C. CHELTUIELI IN AVANS (ct.471)', 10, N'(471,d)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'D. DATORII: SUMELE CARE TREBUIE PLATITE INTR-O PERIOADA DE PANA LA UN AN (ct.161+162+166+167+168-169+269+401+403+404+405+408+419+421+423+424 +426+427+4281+431+437+4381+441+4423+4428+444+446+447+4481+451+453+455+456+457+4581+ 462+473+509+5186+519)', 11, N'(161, c) + (162, c) + (166, c) + (168, c) - (169, c) + (269, c) + (401, c) + (403, c) + (404, c) + (405, c) + (408, c) + (419, c) + (421, c) + (423, c) + (424, c) + (426, c) + (427, c) + (4281, c) + (431, c) + (437, c) + (4381, c) + (441, c) + (4423, c) + (444, c) + (446, c) + (447, c) + (4481, c)  + (451, c) + (455, c) + (456, c) + (457, c) + (4581, c) + (462, c) + (473, c) + (509, c)  + (5186, c)  + (519, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'E. ACTIVE CIRCULANTE NETE/ DATORII CURENTE NETE (rd. 09+10-11-18)', 12, N'r9+r10-r11-r18')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'F. TOTAL ACTIVE MINUS DATORII CURENTE (rd. 04+12)', 13, N'r4+r12')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'G. DATORII:SUMELE CARE TREBUIE PLATITE INTR-O PERIOADA MAI MARE DE UN AN (ct.161+162+166+167+168-169+269+401+403+404+405+408+419+421+423+424 +426+427+4281+431+437+4381+441+4423+4428+444+446+447+4481+451+453 +455+456+457+4581+462+473+509+5186+519)', 14, N'(167, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'H. PROVIZIOANE (ct. 151)', 15, N'(151, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'I. VENITURI IN AVANS (rd. 17+18), din care:', 16, N'r17 + r18')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'  - subventii pentru investitii (ct. 131+132+133+134+138)', 17, N'(131, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'  - venituri inregistrate în avans (ct. 472)', 18, N'(472, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'J. CAPITAL SI REZERVE', 0, N'(1015, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   I. CAPITAL (rd. 20+21+22) din care:', 19, N'r20+r21+r22')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   - Capital subscris varsat (ct. 1012)', 20, N'(1012, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   - Capital subscris nevarsat (ct. 1011)', 21, N'(1011, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   - Patrimoniul regiei (ct. 1015)', 22, N'(1015, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   II. PRIME DE CAPITAL (ct. 104)', 23, N'(104, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   III. REZERVE DIN REEVALUARE (ct. 105)', 24, N'(105, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   IV. REZERVE (ct. 106)', 25, N'(106, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'      Actiuni proprii (ct. 109)', 26, N'(109, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'      Castiguri legate de instrumentele de capitaluri proprii (ct. 141)', 27, N'')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'      Pierderi legate de intrumentele de capitaluri proprii (ct. 149)', 28, N'')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   V. PROFITUL SAU PIERDEREA REPORTAT (A)                     SOLD C (ct. 117)', 29, N'max[ (117, c) , 0 ]')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'                                                                                                SOLD D (ct. 117)', 30, N'max[ (117, d) , 0 ]')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   VI. PROFITUL SAU PIERDEREA EXERCITIULUI FINANCIAR      SOLD C (ct. 121)', 31, N'max[ (121, c) , 0 ]')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'                                                                                                            SOLD D (ct. 121)', 32, N'max[ (121, d) , 0 ]')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   Repartizarea profitului (ct. 129)', 33, N'(129, d)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   CAPITALURI PROPRII - TOTAL (rd.19+23 +24+25-26+27-28+29-30+31-32-33)', 34, N'r19 + r23 + r24 + r25 - r26 + r27 - r28  + r29 - r30 + r31 - r32 -r33')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   Patrimoniul public (ct. 1016)', 35, N'(1016, c)')
GO

INSERT INTO [Bilant].[c_fb] ([indicator], [nr], [exp])
VALUES (N'   CAPITALURI - TOTAL (rd. 34 + 35)', 36, N'r34 + r35')
GO

IF Object_id('Bilant.c_fbai') IS NULL
    CREATE TABLE [Bilant].[c_fbai] (
  [indicator] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp1] varchar(max) COLLATE Latin1_General_CI_AS  NULL,
  [exp2] varchar(max) COLLATE Latin1_General_CI_AS  NULL,
  [exp3] varchar(max) COLLATE Latin1_General_CI_AS  NULL,
  [indice] numeric(1, 0)  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbai' table  (Records 1 - 39) */

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari necorporale', 0, N'', N'', N'', 1)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Cheltuieli de constituire si cheltuieli de dezvoltare', 1, N'(201, d) + (203, d)', N'(201, d) + (203, d)', N'(201, c) + (203, c)', 1)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Alte imobilizari', 2, N'(205, d) + (207, d) + (208, d)', N'(205, d) + (207, d) + (208, d)', N'(205, c) + (207, c) + (208, c)', 1)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Avansuri si imobilizari necorporale in curs', 3, N'(233, d)', N'(233, d)', N'(233, c)', 1)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'TOTAL (rd. 01 la 03)', 4, N'r1 + r2 + r3', N'r1 + r2 + r3', N'r1 + r2 + r3', 1)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari corporale', 0, N'', N'', N'', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Terenuri', 5, N'(211, d)', N'(211, d)', N'(211, c)', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Constructii', 6, N'(212, d)', N'(212, d)', N'(212, c)', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Instalatii tehnice si masini', 7, N'(2131, d)+(2133, d)', N'(2131, d)+(2133, d)', N'(2131, c)+(2133, c)', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Alte instalatii, utilaje si mobilier', 8, N'(2132, d) + (2134, d) + (214, d)', N'(2132, d) + (2134, d) + (214, d)', N'(2132, c) + (2134,c) + (214, c)', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Avansuri si imobilizari corporale in curs', 9, N'(231, d)+(232,d)', N'(231, d)+(232,d)', N'(231, c)+(232,c)', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'TOTAL  (rd. 05 la 09)', 10, N'r5 + r6 + r7 + r8 + r9', N'r5 + r6 + r7 + r8 + r9', N'r5 + r6 + r7 + r8 + r9', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari financiare', 11, N'(261, d) + (263, d) + (267, d) - (269, c)', N'(261, d) + (263, d) + (267, d) - (269, c)', N'(261, c)  + (263, c) + (267, c) - (269, d)', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'ACTIVE IMOBILIZATE - TOTAL (rd. 4+10+11)', 12, N'r4 + r10 + r11', N'r4 + r10 + r11', N'r4 + r10 + r11', 2)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari necorporale', 0, N'', N'', N'', 3)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Cheltuieli de constituire si cheltuieli de dezvoltare', 13, N'(2801, c) + (2803, c)', N'(2801, c) + (2803, c)', N'(2801, d) + (2803, d)', 3)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Alte imobilizari', 14, N'(2805, c) + (2807, c) + (2808, c)', N'(2805, c) + (2807, c) + (2808, c)', N'(2805, d) + (2807, d) + (2808, d)', 3)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'TOTAL (rd. 13+14)', 15, N'r13 + r14', N'r13 + r14', N'r13 + r14', 3)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari corporale', 0, N'', N'', N'', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Terenuri', 16, N'(2811, c)', N'(2811, c)', N'(2811, d)', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Constructii', 17, N'(2812, c)', N'(2812, c)', N'(2812, d)', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Instalatii tehnice si masini', 18, N'(2813, c)', N'(2813, c)', N'(2813, d)', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Alte instalatii, utilaje si mobilier', 19, N'(2814, c)', N'(2814, c)', N'(2814, d)', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'TOTAL (rd. 16 la 19)', 20, N'r16 + r17 + r18 + r19', N'r16 + r17 + r18 + r19', N'r16 + r17 + r18 + r19', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'AMORTIZARI - TOTAL (rd. 15+20)', 21, N'r15 + r20', N'r15 + r20', N'r15 + r20', 4)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari necorporale', 0, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Cheltuieli de constituire si cheltuieli de dezvoltare', 22, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Alte imobilizari', 23, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Avansuri si imobilizari necorporale in curs', 24, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'TOTAL (rd. 22 la 24)', 25, N'r22 + r23 + r24', N'r22 + r23 + r24', N'r22 + r23 + r24', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari corporale', 0, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Terenuri', 26, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Constructii', 27, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Instalatii tehnice si masini', 28, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Alte instalatii, utilaje si mobilier', 29, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Avansuri si imobilizari corporale in curs', 30, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'TOTAL (rd. 26 la 30)', 31, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'Imobilizari financiare', 32, N'', N'', N'', 6)
GO

INSERT INTO [Bilant].[c_fbai] ([indicator], [nr], [exp1], [exp2], [exp3], [indice])
VALUES (N'AJUSTARI PENTRU DEPRECIERE - TOTAL  (rd. 25+31+32)', 33, N'r25 + r31 + r32
', N'r25 + r31 + r32
', N'r25 + r31 + r32', 6)
GO

IF Object_id('Bilant.c_fbdi1') IS NULL
    CREATE TABLE [Bilant].[c_fbdi1] (
  [indicator] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbdi1' table  (Records 1 - 2) */

INSERT INTO [Bilant].[c_fbdi1] ([indicator], [nr])
VALUES (N'Unităti care au inregistrat profit', 1)
GO

INSERT INTO [Bilant].[c_fbdi1] ([indicator], [nr])
VALUES (N'Unităti care au inregistrat  pierdere', 2)
GO

IF Object_id('Bilant.c_fbdi2') IS NULL
    CREATE TABLE [Bilant].[c_fbdi2] (
  [indicator] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] char(100) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbdi2' table  (Records 1 - 20) */

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Plăti restante - total (rd.04+08+14 la 18 +22), din care:', 3, N'r4+r8+r14+r15+r16+r17+r18+r22')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Furnizori restanti - total (rd.05 la 07), din care:', 4, N'r5+r6+r7')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - peste 30 de zile', 5, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - peste 90 de zile', 6, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - peste 1 an', 7, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' Obligatii restante fată de bugetul  asigurarilor sociale - total                (rd.09 la 13), din care:', 8, N'r9+r10+r11+r12+r13')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - Contributii pentru asigurari sociale de stat datorate de angajatori,     salariati si alte persoane asimilate', 9, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - Contributii pentru fondul asigurarilor sociale de sanatate', 10, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - Contributia pentru pensia suplimentara', 11, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - Contributii pentru bugetul asigurarilor pentru somaj', 12, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - Alte datorii sociale', 13, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Obligatii restante fată de bugetele fondurilor speciale si alte fonduri', 14, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Obligatii restante fată de alti creditori', 15, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Impozite si taxe neplătite la termenul stabilit la bugetul de stat', 16, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Impozite si taxe neplătite la termenul stabilit la bugetele locale', 17, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Credite bancare nerambursate la scadenta - total (rd.19 la 21), din care:', 18, N'r19+r20+r21')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - restante dupa 30 zile', 19, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - restante dupa 90 zile', 20, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N' - restante dupa  1 an', 21, N'')
GO

INSERT INTO [Bilant].[c_fbdi2] ([indicator], [nr], [exp])
VALUES (N'Dobânzi restante', 22, N'')
GO

IF Object_id('Bilant.c_fbdi3') IS NULL
    CREATE TABLE [Bilant].[c_fbdi3] (
  [indicator] char(200) COLLATE Latin1_General_CI_AS NULL,
  [nr] numeric(2, 0)  NULL
    )
    ON [PRIMARY]
GO

INSERT INTO [Bilant].[c_fbdi3] ([indicator], [nr])
VALUES (N'Numarul mediu de salariati', 23)
GO

IF Object_id('Bilant.c_fbdi4') IS NULL
    CREATE TABLE [Bilant].[c_fbdi4] (
  [indicator] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [is_lock] bit  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbdi4' table  (Records 1 - 9) */

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N' IV. Plăti de dobânzi si redevente', 0, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N'Venituri brute din dobânzi plătite de persoanele juridice române către persoanele fizice nerezidente din statele membre ale Uniunii Europene, din care:', 24, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N' -  impozitul datorat la bugetul  de stat', 25, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N'Venituri brute din dobânzi platite de persoanele juridice române catre persoane juridice afiliate*) nerezidente din statele membre ale Uniunii Europene, din care:', 26, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N' -  impozitul datorat la bugetul  de stat', 27, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N'Venituri din redevente plătite de persoanele juridice române către persoane juridice afiliate *)  nerezidente din statele  membre ale Uniunii Europene, din care:', 28, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N' -  impozitul datorat la bugetul  de stat', 29, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N'V. Tichete de masă', 0, 0)
GO

INSERT INTO [Bilant].[c_fbdi4] ([indicator], [nr], [is_lock])
VALUES (N'Contravaloarea tichetelor de masă acordate salariatilor', 30, 0)
GO

IF Object_id('Bilant.c_fbdi5') IS NULL
    CREATE TABLE [Bilant].[c_fbdi5] (
  [indicator] char(200) COLLATE Latin1_General_CI_AS NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] char(200) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbdi5' table  (Records 1 - 4) */

INSERT INTO [Bilant].[c_fbdi5] ([indicator], [nr], [exp])
VALUES (N'VI. Cheltuieli de inovare **) - total (rd.32 la 34), din care:', 31, N'r32+r33+r34')
GO

INSERT INTO [Bilant].[c_fbdi5] ([indicator], [nr], [exp])
VALUES (N' - cheltuieli de inovare finalizate in cursul perioadei', 32, N'')
GO

INSERT INTO [Bilant].[c_fbdi5] ([indicator], [nr], [exp])
VALUES (N' - cheltuieli de inovare in curs de finalizare in cursul perioadei', 33, N'')
GO

INSERT INTO [Bilant].[c_fbdi5] ([indicator], [nr], [exp])
VALUES (N' - cheltuieli de inovare abandonate in cursul perioadei', 34, N'')
GO

IF Object_id('Bilant.c_fbdi6') IS NULL
    CREATE TABLE [Bilant].[c_fbdi6] (
  [indicator] char(248) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] varchar(max) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbdi6' table  (Records 1 - 60) */

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Imobilizări financiare, în sume brute (rd. 36 + 42), din care', 35, N'r36 + r42')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Actiuni detinute la entitătile afiliate, interese de participare, alte titluri imobilizate si obligatiuni pe termne lung, în sume brute (rd. 37 la 41), din care:', 36, N'r37+r38+r39+r40+r41')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni cotate', 37, N'(261,d) + (263,d) + (265,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni necotate', 38, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - părti sociale', 39, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - obligatiuni', 40, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni emise de organismele de plasament colectiv (inclusiv de SIF-uri)', 41, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Creante imobilizate, în sume brute (rd. 43 + 44), din care:', 42, N'r43+r44')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - creante imobilizate în lei si exprimate în lei, a caror decontare se face in functie de cursul unei valute (din ct. 267)', 43, N'(267, d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - creante imobilizate în valută (din ct. 267)', 44, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Creante comerciale, avansuri acordate furnizorilor si alte conturi asimilate, in sume brute (ct. 4092 + 411 + 413 + 418)', 45, N'(4092, d) +(411, d)+(413, d)+(418, d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Creante in legatura cu personalul si conturi asimilate (ct. 425 + 4282)', 46, N'(425, d) +(4282, d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Creante in legatura cu bugetul asigurarilor sociale si bugetul statului (ct. 431 + 437 + 4382 + 441 + 4424 + 4428 + 444 + 445 + 446 + 447 + 4482)', 47, N'(431,d) + (437,d) + (4382,d) + (441,d) + (4424,d) + max[(4428,d),0] + (444,d) + (445,d) + (446,d) + (447,d) + (4482,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Alte creante (ct. 451 + 453 + 456 + 4582 + 461 + 471 + 473)', 48, N'(451,d) + (453,d) + (456,d) + (4582,d) + (461,d) + (471,d) + (473,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Dobanzi de incasat (ct. 5187)', 49, N'(5187,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Investitii pe termen scurt, in sume brute (ct. 501 + 505 + 506 din ct.508) (rd. 51 la 55), din care:', 50, N'r51+r52+r53+r54+r55')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni cotate', 51, N'(501,d) + (505,d) + (506,d) + (508,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni necotate', 52, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - parti sociale', 53, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - obligatiuni', 54, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'    - actiuni emise de organismele de plasament colectiv (inclusiv de SIF-uri)', 55, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Alte valori de incasat (ct. 5113 + 5114)', 56, N'(5113,d) + (5114,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Casa in lei si in valuta (rd. 58 + 59), din care:', 57, N'r58 + r59')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei (ct. 5311)', 58, N'(5311,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta (ct. 5314)', 59, N'(5314,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Conturi curente la banci in lei si in valuta (rd. 61 + 62), din care:', 60, N'r61+r62')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei (ct. 5121)', 61, N'(5121,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta (ct. 5124)', 62, N'(5124,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Alte conturi curente la banci si acreditive (rd. 64 + 65), din care:', 63, N'r64+r65')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - sume in curs de decontare, acreditive si alte valori de incasat, in lei (ct. 5112 + 5125 + 5411)', 64, N'(5112,d) + (5125,d) + (5411,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - sume in curs de decontare si acreditive in valuta  (ct. 5125 + 5412)', 65, N'(5412,d)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Datorii (rd. 67 + 70 + 73 + 76 + 79 + 82 + 83 + 86 la 90), din care:', 66, N'r67 + r70 + r73 + r76 + r79 + r82 + r83 + r86 + r87 + r88 + r89 + r90')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Imprumuturi din emisiuni de obligatiuni si dobanzile aferente, in sume brute (ct. 161 + 1681) (rd. 68 + 69), din care:', 67, N'r68 + r69')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei', 68, N'(161,c) + (1681,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta', 69, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Credite bancare interne pe termen scurt si dobanzile aferente (ct. 5191 + 5192 + 5197 + din ct.5198) (rd. 71 + 72), din care:', 70, N'r71 + r72')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei', 71, N'(5191,c) + (5192,c) + (5197,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta', 72, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Credite bancare externe pe termen scurt si dobanzile aferente (ct. 5193 + 5194 + 5195 + din ct.5198) (rd. 74 + 75), din care:', 73, N'r74 + r75')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei', 74, N'(5193,c) + (5194,c) + (5195,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta', 75, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Credite bancare pe termen lung si dobanzile aferente (ct. 1621 + 1622 + 1627 + din ct.1682) (rd. 77 + 78), din care:', 76, N'r77 + r78')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei', 77, N'(1621,c) + (1622,c) + (1627,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta', 78, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Credite externe pe termen lung (ct. 1623 + 1624 + 1625 + din ct.1682) (rd. 80 + 81), din care:', 79, N'r80 + r81')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei', 80, N'(1623,c) + (1624,c) + (1625,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta', 81, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Credite de la trezoreria statului (ct. 1626 + din ct. 1682)', 82, N'(1626,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Alte imprumuturi si dobanzile aferente (ct. 166 + 167 + 1685 + 1686 + 1687) (rd. 84 + 85), din care:', 83, N'r84 + r85')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in lei si exprimate în lei, a caror decontare se face in functie de cursul inei valute', 84, N'(166,c) + (167,c) + (1685,c) + (1686,c) + (1687,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - in valuta', 85, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Datorii comerciale, avansuri primite de la clienti si alte conturi asimilate, în sume brute (ct. 401 + 403 + 404 + 405 + 408 + 419)', 86, N'(401,c) + (403,c) + (404,c) + (405,c) + (408,c) + (419,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Datorii in legatura cu personalul si conturi asimilate (ct. 421 + 423 + 424 + 426 + 427 + 4281)', 87, N'(421,c) + (423,c) + (424,c) + (426,c) + (427,c) + (4281,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Datorii in legatura cu bugetul asigurarilor sociale si bugetul statului (ct. 431 + 437 + 4381 + 441 + 4423 + 4428 + 444 + 446 + 447 + 4481)', 88, N'(431,c) + (437,c) + (4381,c) + (441,c) + (4423,c) + max[(4428,c),0] + (444,c) + (446,c) + (447,c) + (4481,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Alte datorii (ct. 451 + 453 + 455 + 456 + 457 + 4581 + 462 + 472 + 473 + 269 + 509)', 89, N'(451,c) + (453,c) + (455,c) + (456,c) + (457,c) + (4581,c) + (462,c) + (472,c) + (473,c) + (269,c) + (509,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - Dobanzi de platit (ct. 5186)', 90, N'(5186,c)')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   Capital subscris varsat (ct. 1012) (rd. 92 la 94), din care:', 91, N'r92 + r93 + r94')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni cotate', 92, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - actiuni necotate', 93, N'')
GO

INSERT INTO [Bilant].[c_fbdi6] ([indicator], [nr], [exp])
VALUES (N'   - parti sociale', 94, N'(1012,c)')
GO

IF Object_id('Bilant.c_fbdi7') IS NULL
    CREATE TABLE [Bilant].[c_fbdi7] (
  [indicator] char(248) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] varchar(max) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbdi7' table  (Records 1 - 1) */

INSERT INTO [Bilant].[c_fbdi7] ([indicator], [nr], [exp])
VALUES (N'Cheltuieli cu colaboratorii (ct. 621)', 95, N'(621, d)')
GO

IF Object_id('Bilant.c_fbnote') IS NULL
    CREATE TABLE [Bilant].[c_fbnote] (
  [n1] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n2] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n3] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n4] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n5] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n6] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n7] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n8] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n9] varchar(max) COLLATE Latin1_General_CI_AS NULL,
  [n10] varchar(max) COLLATE Latin1_General_CI_AS NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbnote' table  (Records 1 - 1) */

INSERT INTO [Bilant].[c_fbnote] ([n1], [n2], [n3], [n4], [n5], [n6], [n7], [n8], [n9], [n10])
VALUES (N'Nota 1
Active imobilizate 
                                                                                                         - lei -
+-------------+------------------------------------------------+-----------------------------------------------+
|             |                                                |            Ajustari de valoare***)            |
|             |               Valoarea bruta**)                |   (amortizari si ajustari pentru depreciere   |
|  Denumirea  |                                                |           sau pierdere de valoare)            |
| elementului +------------+----------+-----------+------------+------------+------------+--------+------------+
|     de      |  Sold la   |          |  Cedari,  |  Sold la   |  Sold la   |  Ajustari  |        |  Sold la   |
|imobilizare*)| inceputul  | Cresteri |transferuri| sfarsitul  | inceputul  |inregistrate|Reduceri| sfarsitul  |
|             |exercitiului|  ****)   |  si alte  |exercitiului|exercitiului| in cursul  |  sau   |exercitiului|
|             | financiar  |          | reduceri  | financiar  | financiar  |exercitiului|reluari | financiar  |
|             |            |          |           |            |            | financiar  |        |            |
+-------------+------------+----------+-----------+------------+------------+------------+--------+------------+
|      0      |     1      |    2     |     3     | 4 = 1+2-3  |     5      |     6      |   7    | 8 = 5+6-7  |
+-------------+------------+----------+-----------+------------+------------+------------+--------+------------+
+-------------+------------+----------+-----------+------------+------------+------------+--------+------------+
+-------------+------------+----------+-----------+------------+------------+------------+--------+------------+
+-------------+------------+----------+-----------+------------+------------+------------+--------+------------+
+-------------+------------+----------+-----------+------------+------------+------------+--------+------------+
 
*) Cheltuielile de constituire si cheltuielile de dezvoltare vor fi detaliate, prezentandu-se motivele imobilizarii si perioada de amortizare, cu justificarea acesteia. 
**) Modificarile valorii brute se vor prezenta plecand de la costul de achizitie sau costul de productie pentru fiecare element de imobilizare, in functie de tratamentele contabile aplicate. 
In cazul in care durata contractului sau durata de utilizare a elementelor de natura cheltuielilor de dezvoltare depaseste cinci ani, aceasta trebuie prezentata in notele explicative, impreuna cu motivele care au determinat-o. 
In cazul fondului comercial amortizat intr-o perioada de peste cinci ani, aceasta perioada nu trebuie sa depaseasca durata de utilizare economica a activului si trebuie sa fie prezentata si justificata in notele explicative. 
***) Se vor prezenta duratele de viata sau ratele de amortizare utilizate, metodele de amortizare si ajustarile care privesc exercitiile anterioare. 
****) Se vor prezenta separat cresterile de valoare aparute din procesul de dezvoltare interna.', N'Nota 2
Provizioane 
                                                                           - lei -
+---------------+-----------------+----------------------------+-----------------+
|   Denumirea   |Sold la inceputul|       Transferuri**)       |Sold la sfarsitul|
|provizionului*)|  exercitiului   +-------------+--------------+  exercitiului   |
|               |    financiar    |   in cont   |   din cont   |    financiar    |
+---------------+-----------------+-------------+--------------+-----------------+
|       0       |        1        |      2      |      3       |    4 = 1+2-3    |
+---------------+-----------------+-------------+--------------+-----------------+
+---------------+-----------------+-------------+--------------+-----------------+
+---------------+-----------------+-------------+--------------+-----------------+

 
*) Provizioanele prezentate in bilant la "Alte provizioane" trebuie descrise in notele explicative, daca acestea sunt semnificative. 
**) Cu explicarea naturii, sursei sau destinatiei acestora. 
', N'Nota 3
Repartizarea profitului*) 
                                                                         - lei -
+------------------------------------------------------------------------------+
|            Destinatia profitului            |              Suma              |
+---------------------------------------------+--------------------------------+
|Profit net de repartizat:                    |                                |
+---------------------------------------------+--------------------------------+
|   - rezerva legala                          |                                |
+---------------------------------------------+--------------------------------+
|   - acoperirea pierderii contabile          |                                |
+---------------------------------------------+---------------------------------
|   - dividende etc.                          |                                |
+---------------------------------------------+---------------------------------
|Profit nerepartizat                          |                                |
+------------------------------------------------------------------------------+
 
*) In cazul acoperirii pierderii contabile reportate, se vor prezenta sursele de acoperire a acesteia.', N'Nota 4
Analiza rezultatului din exploatare 
                                                                                    - lei -
+-------------------------------------------------------------------+---------------------+
|                                                                   | Exercitiu financiar |
|                      Denumirea indicatorului                      +-----------+---------+
|                                                                   | Precedent | Curent  |
+-------------------------------------------------------------------+-----------+----------
|                                 0                                 |     1     |    2    |
+-------------------------------------------------------------------+-----------+---------+
| 1. Cifra de afaceri neta                                          |           |         |
+-------------------------------------------------------------------+-----------+---------+
| 2. Costul bunurilor vandute si al serviciilor prestate (3 + 4 + 5)|           |         |
+-------------------------------------------------------------------+-----------+---------+
| 3. Cheltuielile activitatii de baza                               |           |         |
+-------------------------------------------------------------------+-----------+---------+
| 4. Cheltuielile activitatilor auxiliare                           |           |         |
+-------------------------------------------------------------------+-----------+---------+
| 5. Cheltuielile indirecte de productie                            |           |         |
+-------------------------------------------------------------------+-----------+---------+
| 6. Rezultatul brut aferent cifrei de afaceri nete (1 - 2)         |           |         |
+-------------------------------------------------------------------+-----------+----------
| 7. Cheltuielile de desfacere                                      |           |         |
+-------------------------------------------------------------------+-----------+---------+
| 8. Cheltuieli generale de administratie                           |           |         |
+-------------------------------------------------------------------+-----------+----------
| 9. Alte venituri din exploatare                                   |           |         |
+-------------------------------------------------------------------+-----------+----------
|10. Rezultatul din exploatare (6 - 7 - 8 + 9)                      |           |         |
+-----------------------------------------------------------------------------------------+', N'Nota 5
Situatia creantelor si datoriilor 
                                                                         - lei -
+--------------------+--------------------------+------------------------------+
|                    |           Sold           |    Termen de lichiditate     |
|      Creante       |       la sfarsitul       +----------------+-------------+
|                    |  exercitiului financiar  |    Sub 1 an    | Peste 1 an  |
+--------------------+--------------------------+----------------+-------------+
|         0          |        1 = 2 + 3         |       2        |      3      |
+--------------------+--------------------------+----------------+-------------+
|Total, din care:    |                          |                |             |
+--------------------+--------------------------+----------------+-------------+
+--------------------+--------------------------+----------------+-------------+
+--------------------+--------------------------+----------------+-------------+
+------------------------------------------------------------------------------+
|                                                                        - lei |
---------------------+--------------------------+------------------------------+
|                    |           Sold           |   Termen de exigibilitate    |
|     Datorii*)      |       la sfarsitul       +--------+---------+-----------+
|                    |  exercitiului financiar  |Sub 1 an| 1-5 ani |Peste 5 ani|
+--------------------+--------------------------+--------+---------+-----------+
|         0          |        1 = 2 + 3 + 4     |   2    |    3    |     4     |
+--------------------+--------------------------+--------+---------+------------
|Total, din care:    |                          |        |         |           |
+--------------------+--------------------------+--------+---------+-----------+
+--------------------+--------------------------+--------+---------+-----------+
+--------------------+--------------------------+--------+---------+-----------+
+------------------------------------------------------------------------------+
 
*) Se vor mentiona urmatoarele informatii: 
a) clauzele legate de achitarea datoriilor si rata dobanzii aferente imprumuturilor; 
b) datoriile pentru care s-au depus garantii sau au fost efectuate ipotecari: 
- valoarea datoriei; 
- valoarea si natura garantiilor; 
c) valoarea obligatiilor pentru care s-au constituit provizioane; 
d) valoarea obligatiilor privind plata pensiilor. 
', N'Nota 6
Principii, politici si metode contabile
 
Se vor prezenta: 
a) Reglementarile contabile aplicate la intocmirea si prezentarea situatiilor financiare anuale. 
b) Abaterile de la principiile si politicile contabile, metodele de evaluare si de la alte prevederi din reglementarile contabile, mentionandu-se: 
- natura; 
- motivele; 
- evaluarea efectului asupra activelor si datoriilor, pozitiei financiare si a profitului sau pierderii. 
c) Daca valorile prezentate in situatiile financiare nu sunt comparabile, absenta comparabilitatii 
trebuie prezentata in notele explicative, insotita de comentarii relevante. 
d) Valoarea reziduala pentru imobilizari stabilita in situatia in care nu se cunoaste pretul de achizitie sau costul de productie al acesteia. 
e) Suma dobanzilor incluse in costul activelor imobilizate si circulante cu ciclu lung de fabricatie. 
f) in cazul reevaluarii imobilizarilor corporale: 
- elementele supuse reevaluarii, precum si metodele prin care sunt determinate valorile rezultate in urma reevaluarii; 
- valoarea la cost istoric a imobilizarilor reevaluate; 
- tratamentul in scop fiscal al rezervei din reevaluare; 
- modificarile rezervei din reevaluare: 
	- valoarea rezervei din reevaluare la inceputul exercitiului financiar; 
	- diferentele din reevaluare transferate la rezerva din reevaluare in cursul exercitiului financiar; 
	- sumele capitalizate sau transferate intr-un alt mod din rezerva din reevaluare in cursul exercitiului            financiar, prezentandu-se natura oricarui astfel de transfer, cu respectarea legislatiei in vigoare; 
	- valoarea rezervei din reevaluare la sfarsitul exercitiului financiar. 
g) Daca activele fac obiectul ajustarilor exceptionale de valoare exclusiv in scop fiscal, suma ajustarilor si motivele pentru care acestea au fost efectuate trebuie prezentate in notele explicative. 
h) Daca valoarea prezentata in bilant, rezultata dupa aplicarea metodelor FIFO, CMP sau LIFO, difera in mod semnificativ, la data bilantului, de valoarea determinata pe baza ultimei valori de piata cunoscute inainte de data bilantului, valoarea acestei diferente trebuie prezentata in notele explicative ca total, pe categorii de active fungibile. 

', N'Nota 7
Participatii si surse de finantare
 
Se vor prezenta urmatoarele informatii: 
a) se mentioneaza existenta oricaror certificate de participare, valori mobiliare, obligatiuni convertibile, cu prezentarea informatiilor cerute in Subsectiunea 8.2; 
b) capital social subscris/patrimoniul entitatii; 
c) numarul si valoarea totala a fiecarui tip de actiuni emise, mentionandu-se daca au fost integral varsate si, dupa caz, numarul actiunilor pentru care s-a cerut, fara rezultat, efectuarea varsamintelor; 
d) actiuni rascumparabile: 
- data cea mai apropiata si data limita de rascumparare; 
- caracterul obligatoriu sau neobligatoriu al rascumpararii; 
- valoarea eventualei prime de rascumparare; 
e) actiuni emise in timpul exercitiului financiar: 
- tipul de actiuni; 
- numar de actiuni emise; 
- valoarea nominala totala si valoarea incasata la distribuire; 
- drepturi legate de distributie: 
	- numarul, descrierea si valoarea actiunilor corespunzatoare; 
	- perioada de exercitare a drepturilor; 
	- pretul platit pentru actiunile distribuite; 
f) obligatiuni emise: 
- tipul obligatiunilor emise; 
- valoarea emisa si suma primita pentru fiecare tip de obligatiuni; 
- obligatiuni emise de entitate, detinute de o persoana nominalizata sau imputernicita de aceasta: 
	- valoarea nominala; 
	- valoarea inregistrata in momentul platii.', N'Nota 8
Informatii privind salariatii si membrii organelor de administratie,conducere si de supraveghere
 
Se vor face mentiuni cu privire la: 
a) indemnizatiile acordate membrilor organelor de administratie, conducere si de supraveghere; 
b) obligatiile contractuale cu privire la plata pensiilor catre fostii membri ai organelor de administratie, conducere si supraveghere, indicandu-se valoarea totala a angajamentelor pentru fiecare categorie. 
c) valoarea avansurilor si a creditelor acordate membrilor organelor de administratie, conducere si de supraveghere in timpul exercitiului: 
- rata dobanzii; 
- principalele clauze ale creditului; 
- suma rambursata pana la acea data; 
- obligatii viitoare de genul garantiilor asumate de entitate in numele acestora; 
d) salariati: 
- numar mediu, cu defalcarea pe fiecare categorie; 
- salarii platite sau de platit, aferente exercitiului; 
- cheltuieli cu asigurarile sociale; 
- alte cheltuieli cu contributiile pentru pensii.', N'Nota 9
Exemple de calcul si analiza a principalilor indicatori economico-financiari

 
1. Indicatori de lichiditate: 

a) Indicatorul lichiditatii curente

     Active curente (Indicatorul capitalului circulant) 
     --------------------------------------------------
                 Datorii curente
 
- valoarea recomandata acceptabila - in jurul valorii de 2; 
- ofera garantia acoperirii datoriilor curente din activele curente.
 
b) Indicatorul lichiditatii imediate 

     Active curente - Stocuri (Indicatorul test acid) 
     -----------------------------------------------
                   Datorii curente
 
2. Indicatori de risc: 

a) Indicatorul gradului de indatorare 

Capital imprumutat              Capital imprumutat
------------------ x 100  sau   ------------------ x 100
  Capital propriu                Capital angajat
 
unde: 
- capital imprumutat = credite peste un an; 
- capital angajat = capital imprumutat + capital propriu. 

b) Indicatorul privind acoperirea dobanzilor - determina de cate ori entitatea poate achita cheltuielile cu dobanda. 
Cu cat valoarea indicatorului este mai mica, cu atat pozitia entitatii este considerata mai riscanta.
 
Profit inaintea platii dobanzii si impozitului pe profit
--------------------------------------------------------  =   Numar de ori
                 Cheltuieli cu dobanda
 
3. Indicatori de activitate (indicatori de gestiune) - furnizeaza informatii cu privire la: 
- Viteza de intrare sau de iesire a fluxurilor de trezorerie ale entitatii; 
- Capacitatea entitatii de a controla capitalul circulant si activitatile comerciale de baza ale entitatii; 
- Viteza de rotatie a stocurilor (rulajul stocurilor) - aproximeaza de cate ori stocul a fost rulat de-a lungul exercitiului financiar 

Costul vanzarilor
-------------------     =     Numar de ori
   Stoc mediu
 
sau 

Numar de zile de stocare - indica numarul de zile in care bunurile sunt stocate in unitate 

   Stoc mediu
------------------       x       365
Costul vanzarilor
 
- Viteza de rotatie a debitelor-clienti 
	- calculeaza eficacitatea entitatii in colectarea creantelor sale; 
	- exprima numarul de zile pana la data la care debitorii isi achita datoriile catre entitate.
 
Sold mediu clienti
-------------------      x      365
 Cifra de afaceri
 
O valoare in crestere a indicatorului poate indica probleme legate de controlul creditului acordat clientilor si, in consecinta, creante mai greu de incasat (clienti rau platnici). 

- Viteza de rotatie a creditelor-furnizor - aproximeaza numarul de zile de creditare pe care entitatea il obtine de la furnizorii sai. In mod ideal ar trebui sa includa doar creditorii comerciali. 

       Sold mediu furnizori
-----------------------------------       x       365,
Achizitii de bunuri (fara servicii)
 
unde pentru aproximarea achizitiilor se poate utiliza costul vanzarilor sau cifra de afaceri.
 
- Viteza de rotatie a activelor imobilizate - evalueaza eficacitatea managementului activelor imobilizate prin examinarea valorii cifrei de afaceri generate de o anumita cantitate de active imobilizate
 
 Cifra de afaceri
------------------
Active imobilizate
 
- Viteza de rotatie a activelor totale
 
Cifra de afaceri
----------------
  Total active
 
4. Indicatori de profitabilitate - exprima eficienta entitatii in realizarea de profit din resursele disponibile: 

a) Rentabilitatea capitalului angajat - reprezinta profitul pe care il obtine entitatea din banii investiti in afacere: 

Profit inaintea platii dobanzii si impozitului pe profit
--------------------------------------------------------,
                    Capital angajat
 
unde capitalul angajat se refera la banii investiti in entitate atat de catre actionari, cat si de creditorii pe termen lung, si include capitalul propriu si datoriile pe termen lung sau active totale minus datorii curente. 

b) Marja bruta din vanzari 

Profitul brut din vanzari
---------------------------   x        100
    Cifra de afaceri
 
O scadere a procentului poate scoate in evidenta faptul ca entitatea nu este capabila sa isi controleze costurile de productie sau sa obtina pretul de vanzare optim.
', N'Nota 10
Alte informatii 

Se prezinta: 
a) Informatii cu privire la prezentarea entitatii raportoare, potrivit Subsectiunii 8.2. 
b) Informatii privind relatiile entitatii cu filiale, entitatile asociate sau cu alte entitati in care se detin participatii, cerute potrivit Subsectiunii 8.2. 
c) Bazele de conversie utilizate pentru exprimarea in moneda nationala a elementelor de activ si de pasiv, a veniturilor si cheltuielilor evidentiate initial intr-o moneda straina. 
d) Informatii referitoare la impozitul pe profit: 
- proportia in care impozitul pe profit afecteaza rezultatul din activitatea curenta si rezultatul din activitatea extraordinara; 
- reconcilierea dintre rezultatul exercitiului si rezultatul fiscal, asa cum este prezentat in declaratia de impozit; 
- masura in care calcularea profitului sau pierderii exercitiului financiar a fost afectata de o evaluare a elementelor care, prin derogare de la principiile contabile generale si regulile contabile de evaluare, a fost efectuata in exercitiul financiar curent sau intr-un exercitiu financiar precedent in vederea obtinerii de facilitati fiscale; 
- impozitul pe profit ramas de plata. 
e) Cifra de afaceri: 
- prezentarea acesteia pe segmente de activitati si pe piete geografice. 
f) Atunci cand evenimentele ulterioare datei bilantului au o asemenea importanta incat neprezentarea lor ar putea afecta capacitatea utilizatorilor situatiilor financiare de a face evaluari si de a lua decizii corecte, o entitate trebuie sa prezinte urmatoarele informatii pentru fiecare categorie semnificativa de astfel de evenimente: 
- natura evenimentului; si 
- o estimare a efectului financiar sau o mentiune conform careia o astfel de estimare nu poate sa fie facuta. 
g) Explicatii despre valoarea si natura: 
- veniturilor si cheltuielilor extraordinare; 
- veniturilor si cheltuielilor inregistrate in avans, 
in situatia in care acestea sunt semnificative. 
h) Ratele achitate in cadrul unui contract de leasing. 
i) In cazul unui leasing financiar, locatorul va prezenta urmatoarele informatii: 
- o descriere generala a contractelor semnificative de leasing; 
- dobanda de incasat aferenta perioadelor viitoare. 
In cazul unui leasing financiar, locatarul va evidentia urmatoarele: 
- o descriere generala a contractelor importante de leasing, incluzand, dar fara a se limita la, urmatoarele: 
	- existenta si conditiile optiunilor de reinnoire sau cumparare; 
	- restrictiile impuse prin contractele de leasing, cum ar fi cele referitoare la datorii suplimentare si alte operatiuni de leasing. 
- dobanda de platit aferenta perioadelor viitoare 
j) Onorariile platite auditorilor/cenzorilor si onorariile platite pentru alte servicii de certificare, servicii de consultanta fiscala si alte servicii decat cele de audit. 
k) Efectele comerciale scontate neajunse la scadenta. 
l) Atunci cand suma de rambursat pentru datorii este mai mare decat suma primita, diferenta se prezinta in notele explicative. 
m) Datoriile probabile si angajamentele acordate. 
n) Angajamentele sub forma garantiilor de orice fel trebuie, in cazul in care nu exista obligatia de a le prezenta ca datorii, sa fie in mod clar prezentate in notele explicative, si trebuie facuta distinctie intre diferitele tipuri de garantii recunoscute de legislatia nationala. De asemenea, trebuie facuta o prezentare separata a oricarei garantii valorice care a fost prevazuta. Angajamentele de acest tip care exista in relatia cu entitatile afiliate trebuie prezentate distinct. 
o) Daca un activ sau o datorie are legatura cu mai mult de un element din formatul de bilant, relatia sa cu alte elemente trebuie prezentata in notele explicative, daca o asemenea prezentare este esentiala pentru intelegerea situatiilor financiare anuale. 
p) Orice detaliere a elementelor din situatiile financiare anuale, atunci cand aceste elemente sunt semnificative si sunt relevante utilizatorii situatiilor financiare.
')
GO

IF Object_id('Bilant.c_fbnote2') IS NULL
    CREATE TABLE [Bilant].[c_fbnote2] (
  [denumire] char(100) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp1] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [exp2] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [exp3] char(200) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbnote2' table  (Records 1 - 23) */

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'I. PROVIZIOANE PENTRU RISCURI SI CHELTUIELI (rd.2-6)', 1, N'r2+r3+r4+r5+r6', N'r2+r3+r4+r5+r6', N'r2+r3+r4+r5+r6')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Provizioane pentru litigii (ct.1511)', 2, N'(1511, c)', N'(1511, c)', N'(1511, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Provizioane pentru garantii acordate clientilor (ct.1512)', 3, N'(1512, c)', N'(1512, c)', N'(1512, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Provizioane pentru dezafectare imobilizari corporale si alte actiuni similare (ct.1513)', 4, N'(1513, c)', N'(1513, c)', N'(1513, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Provizioane pentru restructurare (ct.1514)', 5, N'(1514, c)', N'(1514, c)', N'(1514, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Alte provizioane pentru riscuri si cheltuieli (ct.1518)', 6, N'(1518, c)', N'(1518, c)', N'(1518, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'II. PROVIZIOANE PENTRU DEPRECIEREA STOCURILOR SI PRODUCTIEI ÎN CURS DE EXEC.', 7, N'r8+r9+r10+r11+r12+r13+r14+r15', N'r8+r9+r10+r11+r12+r13+r14+r15', N'r8+r9+r10+r11+r12+r13+r14+r15')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Materii prime  (ct.391)', 8, N'(391, c)', N'(391, c)', N'(391,d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Materiale (ct.392)', 9, N'(392, c)', N'(392, c)', N'(392,d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Productie în curs de executie (ct.393)', 10, N'(393, c)', N'(393, c)', N'(393, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Produse (ct.394)', 11, N'(394, c)', N'(394, c)', N'(394, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Stocuri aflate la terti (ct.395)', 12, N'(395, c)', N'(395, c)', N'(395, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Animale (ct.396)', 13, N'(396, c)', N'(396, c)', N'(396, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Marfuri (ct.397)', 14, N'(397, c)', N'(397, c)', N'(397, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Ambalaje (ct.398)', 15, N'(398, c)', N'(398, c)', N'(398, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'III. PROVIZIOANE PENTRU DEPRECIEREA CREANTELOR', 16, N'r17+r18+r19', N'r17+r18+r19', N'r17+r18+r19')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Clienti  (ct.491)', 17, N'(491, c)', N'(491, c)', N'(491,d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Decontari în cadrul grupului si cu asociatii (ct.495)', 18, N'(495, c)', N'(495, c)', N'(495, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Debitori diversi (ct.496)', 19, N'(496, c)', N'(496, c)', N'(496, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'IV. PROVIZIOANE PENTRU DEPRECIEREA CONTURILOR DE TREZORERIE', 20, N'r21+r22', N'r21+r22', N'r21+r22')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Provizioane pentru deprecierea investitiilor financiare  la societati din cadrul grupului (ct.591)', 21, N'(591, c)', N'(591, c)', N'(591, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'Alte provizioane pentru conturi de trezorerie (ct.592+595+596+598)', 22, N'(592, c)+(596, c)+(598, c)', N'(592, c)+(596, c)+(598, c)', N'(592, d)+(596, d)+(598, d)')
GO

INSERT INTO [Bilant].[c_fbnote2] ([denumire], [nr], [exp1], [exp2], [exp3])
VALUES (N'TOTAL GENERAL (rd.01+07+16+20)', 23, N'r1+r7+r16+r20', N'r1+r7+r16+r20', N'r1+r7+r16+r20')
GO

IF Object_id('Bilant.c_fbnote3') IS NULL
    CREATE TABLE [Bilant].[c_fbnote3] (
  [denumire] char(100) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] char(100) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbnote3' table  (Records 1 - 6) */

INSERT INTO [Bilant].[c_fbnote3] ([denumire], [nr], [exp])
VALUES (N'Profit net de repartizat:', 1, N'r2+r3+r4+r5')
GO

INSERT INTO [Bilant].[c_fbnote3] ([denumire], [nr], [exp])
VALUES (N'  - rezerva legala', 2, N'')
GO

INSERT INTO [Bilant].[c_fbnote3] ([denumire], [nr], [exp])
VALUES (N'  - acoperirea pierderii contabile', 3, N'')
GO

INSERT INTO [Bilant].[c_fbnote3] ([denumire], [nr], [exp])
VALUES (N'  - dividende', 4, N'(457,c)')
GO

INSERT INTO [Bilant].[c_fbnote3] ([denumire], [nr], [exp])
VALUES (N'  - alte rezerve', 5, N'')
GO

INSERT INTO [Bilant].[c_fbnote3] ([denumire], [nr], [exp])
VALUES (N'Profit nerepartizat', 6, N'(1171,c)')
GO

IF Object_id('Bilant.c_fbnote4') IS NULL
    CREATE TABLE [Bilant].[c_fbnote4] (
  [denumire] char(100) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp1] char(200) COLLATE Latin1_General_CI_AS  NULL,
  [exp2] char(200) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbnote4' table  (Records 1 - 10) */

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'1. Cifra de afaceri neta', 1, N'GS("fbpp",10,"an_p")-GS("fbpp",9,"an_p")', N'GS("fbpp",10,"an_c")-GS("fbpp",9,"an_c")')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'2. Costul bunurilor vandute si al serviciilor prestate (3 + 4 + 5)', 2, N'r3+r4+r5', N'r3+r4+r5')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'3. Cheltuielile activitatii de baza', 3, N'GS("fbpp",32,"an_p")-GS("fbpp",21,"an_p")-GS("fbpp",24,"an_p")-GS("fbpp",29,"an_p")', N'GS("fbpp",32,"an_c")-GS("fbpp",21,"an_c")-GS("fbpp",24,"an_c")-GS("fbpp",29,"an_c")')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'4. Cheltuielile activitatilor auxiliare', 4, N'', N'')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'5. Cheltuielile indirecte de productie', 5, N'', N'')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'6. Rezultatul brut aferent cifrei de afaceri nete (1 - 2)', 6, N'r1-r2', N'r1-r2')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'7. Cheltuielile de desfacere', 7, N'', N'')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'8. Cheltuieli generale de administratie', 8, N'GS("fbpp",21,"an_p")+GS("fbpp",24,"an_p")+GS("fbpp",29,"an_p")', N'GS("fbpp",21,"an_c")+GS("fbpp",24,"an_c")+GS("fbpp",29,"an_c")')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'9. Alte venituri din exploatare', 9, N'GS("fbpp",9,"an_p")', N'GS("fbpp",9,"an_c")')
GO

INSERT INTO [Bilant].[c_fbnote4] ([denumire], [nr], [exp1], [exp2])
VALUES (N'10. Rezultatul din exploatare (6 - 7 - 8 + 9)', 10, N'r6-r7-r8+r9', N'r6-r7-r8+r9')
GO

IF Object_id('Bilant.c_fbnote5') IS NULL
    CREATE TABLE [Bilant].[c_fbnote5] (
  [denumire] char(200) COLLATE Latin1_General_CI_AS NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] char(100) COLLATE Latin1_General_CI_AS  NULL,
  [indice] numeric(1, 0)  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbnote5' table  (Records 1 - 37) */

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'CREANTE', 0, N'', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Creante din participatii sume datorate de filiale interese de participare dobânzi (ct.261,263,265)', 1, N'(261,d)+(263,d)+(265,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Imprumuturi acordate pe termen lung si dobânzi aferente (ct.2673,2674)', 2, N'(2673,d)+(2674,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Actiuni proprii - active imobilizate (ct.2677)', 3, N'', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Alte creante imobilizate (ct.2671,2675,2676,2678,2679)', 4, N'(2671,d)+(2675,d)+(2676,d)+(2678,d) +(2679,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'I. CREANTE DIN ACTIVE IMOBILIZATE- TOTAL (rd.01 la 04)', 5, N'r1+r2+r3+r4', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Furnizori debitori (ct.4092)', 6, N'(4092,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Clienti (ct.411+413+418)', 7, N'(411,d)+(413,d)+(418,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Creante personal si asigurari sociale (ct.425+4282+431+437+4382)', 8, N'(425,d)+(4282,d)+(431,d)+(437,d)+(4382,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Impozit pe profit (ct.441)', 9, N'max((441,d) ,0)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Taxa pe valoarea adaugata (ct.4424+4428)', 10, N'(4424,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Alte creante cu statul si institutii publice (ct.444,445,446,447,4482)', 11, N'(444,d) +(445,d) +(446,d) +(447,d) +(4482,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Decontari cu grupul si alte creante (ct.451)', 12, N'(451,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Debitori diversi (ct.456+4582+461-491-495-496)', 13, N'(456,d)+(4582,d)+(461,d)-(491,d)-(495,c)-(496,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'II. CREANTE DIN ACTIVE CIRCULANTE - TOTAL (rd. 06 la 13 )', 14, N'r6+r7+r8+r9+r10+r11+r12+r13', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'III. CHELTUIELI INREGISTRATE IN AVANS (ct.471)', 15, N'(471,d)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'TOTAL CREANTE (rd. 05+14+15)', 16, N'r5+r14+r15', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'DATORII', 0, N'', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Imprumuturi din emisiuni de obligatiuni  (ct.161)', 17, N'(161,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Credite bancare pe termen lung (ct.1621+1623+1624+1625+1626+1627)', 18, N'(1621,c)+(1623,c)+(1624,c)+(1625,c)+(1626,c)+(1627,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Credite bancare pe termen lung nerambursate la scadenta (ct.1622)', 19, N'(1622,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Datorii ce privesc imobilizarile financiare (ct.166)', 20, N'(166,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Credite bancare pe termen scurt (ct.5191+5192+5193+5194+5195+5196+5197)', 21, N'(5191,c)+(5192,c)+(5193,c)+(5194,c)+(5195,c)+(5196,c)+(5197,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Dobanzi (ct.168+5186+5198)', 22, N'(168,c)+(5186,c)+(5198,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Alte imprumuturi si datorii financiare (ct.167+509)', 23, N'(167,c)+(509,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'TOTAL DATORII FINANCIARE SI ASIMILATE (rd. 17 la 23)', 24, N'r17+r18+r19+r20+r21+r22+r23', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Furnizori (ct.401+403+404+405+408)', 25, N'(401,c)+(403,c)+(404,c)+(405,c)+(408,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Clienti creditori (ct.419)', 26, N'(419,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Datorii cu personalul si asigurarile sociale (ct.421+423+424+425+426+427+4281+431+437+438)', 27, N'(421,c)+(423,c)+(424,c)+(425,c)+(426,c)+(427,c)+(4281,c)+(431,c)+(437,c)+(438,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Impozit pe profit (ct.441)', 28, N'max((441,c) ,0)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Taxa pe valoarea adaugata (ct.4423+4428)', 29, N'(4423,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Alte datorii fata de stat si institutiile publice (ct.444+445+446+447+4481)', 30, N'(444,c)+(445,c)+(446,c)+(447,c)+(4481,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Decontari cu grupul si alte conturi cu asociati (ct.451+455+457+4581+481+482)', 31, N'(451,c)+(455,c)+(457,c)+(4581,c)+(481,c)+(482,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Creditori diversi (ct.462+473)', 32, N'(462,c)+max((473,c),0)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'ALTE DATORII - TOTAL (rd.25 la 32)', 33, N'r25+r26+r27+r28+r29+r30+r31+r32', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'Venituri inregistrate in avans (ct.472)', 34, N'(472,c)', 0)
GO

INSERT INTO [Bilant].[c_fbnote5] ([denumire], [nr], [exp], [indice])
VALUES (N'TOTAL DATORII (rd. 24+33+34)', 35, N'r24+r33+r34', 0)
GO

IF Object_id('Bilant.c_fbnote9') IS NULL
    CREATE TABLE [Bilant].[c_fbnote9] (
  [denumire] char(250) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] varchar(max) COLLATE Latin1_General_CI_AS  NULL,
  [detalii] varchar(max) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbnote9' table  (Records 1 - 16) */

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'1. Indicatori de lichiditate', 0, N'', N'')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'a) Indicatorul lichiditatii curente', 1, N'GS("fb",9,"an_c")/GS("fb",11,"an_c")', N'Active curente (Indicatorul capitalului circulant) 
     --------------------------------------------------
                 Datorii curente
 
- valoarea recomandata acceptabila - in jurul valorii de 2; 
- ofera garantia acoperirii datoriilor curente din activele curente.')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'b) Indicatorul lichiditatii imediate', 2, N'(GS("fb",9,"an_c")-GS("fb",5,"an_c"))/GS("fb",11,"an_c")', N'Active curente - Stocuri (Indicatorul test acid) 
     -----------------------------------------------
                   Datorii curente')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'2. Indicatori de risc:', 0, N'', N'')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'a) Indicatorul gradului de indatorare', 3, N'(GS("fb",14,"an_c")/GS("fb",36,"an_c"))*100', N'Capital imprumutat                        Capital imprumutat
    ------------------           x 100  sau      ------------------           x 100
  Capital propriu                                Capital angajat
 
unde: 
- capital imprumutat = credite peste un an; 
- capital angajat = capital imprumutat + capital propriu.')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'b) Indicatorul privind acoperirea dobanzilor', 4, N'iif(GS("fbpp",46,"an_c")>0,(GS("fbpp",64,"an_c")-GS("fbpp",62,"an_c")-GS("fbpp",46,"an_c"))/GS("fbpp",46,"an_c"),0)', N'Determina de cate ori entitatea poate achita cheltuielile cu dobanda.             
Cu cat valoarea indicatorului este mai mica, cu atat pozitia entitatii este considerata mai riscanta.
 
Profit inaintea platii dobanzii si impozitului pe profit
-------------------------------------------------------- 				 =   Numar de ori
                 Cheltuieli cu dobanda')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'3. Indicatori de activitate (indicatori de gestiune)', 0, N'', N'Furnizeaza informatii cu privire la: 
- Viteza de intrare sau de iesire a fluxurilor de trezorerie ale entitatii; 
- Capacitatea entitatii de a controla capitalul circulant si activitatile comerciale de baza ale entitatii;')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'a) Viteza de rotatie a stocurilor (rulajul stocurilor)', 5, N'iif(GS("fb",5,"an_c")>0,GS("fbpp",14,"an_c")/GS("fb",5,"an_c"),0)', N'aproximeaza de cate ori stocul a fost rulat de-a lungul exercitiului financiar 

Costul vanzarilor
-------------------     =     Numar de ori
   Stoc mediu')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'b) Viteza de rotatie a stocurilor (numar de zile de stocare)', 6, N'iif(GS("fbpp",14,"an_c")>0,GS("fb",5,"an_c")/GS("fbpp",14,"an_c"),0)*356', N'indica numarul de zile in care bunurile sunt stocate in unitate 

   Stoc mediu
------------------       x       365
Costul vanzarilor')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'c) Viteza de rotatie a debitelor-clienti', 7, N'iif(GS("fbpp",1,"an_c")>0,GS("fbnote5",7,"an_c")/GS("fbpp",1,"an_c"),0)*365', N'- calculeaza eficacitatea entitatii in colectarea creantelor sale; 
- exprima numarul de zile pana la data la care debitorii isi achita datoriile catre entitate.
 
Sold mediu clienti
-------------------           x      365
 Cifra de afaceri
 
O valoare in crestere a indicatorului poate indica probleme legate de controlul creditului acordat clientilor si, in consecinta, creante mai greu de incasat (clienti rau platnici). 
')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'd) Viteza de rotatie a creditelor-furnizor', 8, N'iif(GS("fbpp",1,"an_c")>0,GS("fbnote5",25,"an_c")/GS("fbpp",1,"an_c"),0)*365', N'aproximeaza numarul de zile de creditare pe care entitatea il obtine de la furnizorii sai. In mod ideal ar trebui sa includa doar creditorii comerciali. 

       Sold mediu furnizori
-----------------------------------               x       365,
Achizitii de bunuri (fara servicii)
 
unde pentru aproximarea achizitiilor se poate utiliza costul vanzarilor sau cifra de afaceri.')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'e) Viteza de rotatie a activelor imobilizate', 9, N'iif(GS("fb",4,"an_c")>0,GS("fbpp",1,"an_c")/GS("fb",4,"an_c"),0)', N'evalueaza eficacitatea managementului activelor imobilizate prin examinarea valorii cifrei de afaceri generate de o anumita cantitate de active imobilizate
 
 Cifra de afaceri
------------------
Active imobilizate')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'f) Viteza de rotatie a activelor totale', 10, N'GS("fbpp",1,"an_c")/(GS("fb",4,"an_c")+GS("fb",9,"an_c") +GS("fb",10,"an_c"))', N'Cifra de afaceri
----------------
  Total active')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'4. Indicatori de profitabilitate', 0, N'', N'Exprima eficienta entitatii in realizarea de profit din resursele disponibile')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'a) Rentabilitatea capitalului angajat', 11, N'(GS("fbpp",60,"an_c")+GS("fbpp",46,"an_c"))/(GS("fb",34,"an_c")+GS("fb",14,"an_c"))', N'reprezinta profitul pe care il obtine entitatea din banii investiti in afacere: 

Profit inaintea platii dobanzii si impozitului pe profit
--------------------------------------------------------,
                    Capital angajat
 
unde capitalul angajat se refera la banii investiti in entitate atat de catre actionari, cat si de creditorii pe termen lung, si include capitalul propriu si datoriile pe termen lung sau active totale minus datorii curente. 
')
GO

INSERT INTO [Bilant].[c_fbnote9] ([denumire], [nr], [exp], [detalii])
VALUES (N'b) Marja bruta din vanzari', 12, N'iif(GS("fbpp",3,"an_c")>0,((GS("fbpp",3,"an_c")-GS("fbpp",14,"an_c"))/GS("fbpp",1,"an_c"))*100,0)', N'Profitul brut din vanzari
---------------------------   x        100
    Cifra de afaceri
 
O scadere a procentului poate scoate in evidenta faptul ca entitatea nu este capabila sa isi controleze costurile de productie sau sa obtina pretul de vanzare optim.
')
GO

IF Object_id('Bilant.c_fbpp') IS NULL
    CREATE TABLE [Bilant].[c_fbpp] (
  [indicator] char(150) COLLATE Latin1_General_CI_AS  NULL,
  [nr] numeric(2, 0)  NULL,
  [exp] varchar(max) COLLATE Latin1_General_CI_AS  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Bilant.c_fbpp' table  (Records 1 - 72) */

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'1.Cifra de afaceri neta (rd. 02 la 05)', 1, N'r2+r3+r4+r5')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  Productia vânduta (ct. 701+702+703+704+705+706+708)', 2, N'(701, c) + (702, c) + (703, c) + (704, c) + (705, c) + (706, c) + (708, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  Venituri din vânzarea marfurilor (ct. 707)', 3, N'(707, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  Venituri din dobanzi inregistrate de entitatile al caror obiect de activitate il constituie leasingul (ct. 766)', 4, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  Venituri din subventii de exploatare aferente cifrei de afaceri nete (ct. 7411)', 5, N'(7411, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'2.Variatia stocurilor de produse finite si a productiei in curs de executie (ct. 711)', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'      Sold C', 6, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'      Sold D', 7, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'3.Productia realizata de entitate pentru scopurile sale proprii si capitalizata (ct. 721+722)', 8, N'(721, c) + (722, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'4.Alte venituri din exploatare (ct. 7417+758)', 9, N'(7417, c) + (758, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'VENITURI DIN EXPLOATARE - TOTAL (rd. 01+ 06 - 07 + 08 + 09)', 10, N'r2 +r3 + r4 + r5 + r6 - r7 + r8 + r9')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'5.a)Cheltuieli cu materiile prime si materialele consumabile (ct. 601+602-7412)', 11, N'(601, d) + (602, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'Alte cheltuieli materiale (ct. 603+604+606+608)', 12, N' (603, d) + (604, d) + (606, d) + (608, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  b)Alte cheltuieli externe (cu energia si apa) (ct. 605-7413)', 13, N'(605, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  c)Cheltuieli privind marfurile (ct. 607)', 14, N'(607, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'6.Cheltuieli cu personalul (rd. 16 + 17), din care:', 15, N'r16 + r17')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  a) Salarii si indemnizatii (ct. 641+642-7414)', 16, N'(641, d)+(642 ,d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  b) Cheltuieli cu asigurarile si protectia sociala (ct 645-7415)', 17, N'(645, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'7.a) Ajustari de valoare privind imobilizarile corporale si necorporale (rd. 19 - 20)', 18, N'r19 - r20')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  a.1)  Cheltuieli (ct. 6811 + 6813)', 19, N'(6811, d)  + (6813, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  a.2)  Venituri (ct. 7813)', 20, N'(7813, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  b) Ajustari de valoare privind activele circulante (rd. 22 - 23)', 21, N'r22 - r23')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  b.1)  Cheltuieli (ct. 654 + 6814)', 22, N'(654,d) + (6814,d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  b.2)  Venituri (ct. 754 + 7814)', 23, N'(754,c) + (7814,c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'8.Alte cheltuieli de exploatare (rd. 25 la 28)', 24, N'r25 + r26 + r27 + r28')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'8.1. Cheltuieli privind prestatile externe (ct.611+612+613+614+621+622+623+624+625+626+627+628-7416)', 25, N'(611, d) + (612, d) + (613, d) + (614, d) + (621, d) + (622, d) + (623, d) + (624, d) + (625, d) + (626, d) + (627, d) + (628, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'8.2. Cheltuieli cu impozite, taxe si varsaminte asimilate (ct. 635)', 26, N'(635, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'8.3. Cheltuieli cu despagubiri, donatii si activele cedate (ct. 658)', 27, N'(658, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'Cheltuieli privind dobanzile de refinantare inregistrate de entitatile al caror obiect de acitivitate il constituie leasingul (ct. 666)', 28, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'Ajustari privind provizioanele (rd. 30 - 31)', 29, N'r30 - r31')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - Cheltuieli (ct. 6812)', 30, N'(6812,d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - Venituri (ct. 7812)', 31, N'(7812,c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'CHELTUIELI DE EXPLOATARE - TOTAL (rd.11 la 15 +18 + 21 + 24 + 29)', 32, N'r11 + r12 + r13 + r14 + r15 + r18 + r21 + r24 + r29')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'PROFITUL SAU PIERDEREA DIN EXPLOATARE:', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Profit (rd. 10 - 32)', 33, N'max(r10 - r32,0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Pierdere (rd. 32 - 10)', 34, N'max(r32 - r10,0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'9. Venituri din interese de participare (ct.7611 + 7613)', 35, N'(7611, c) + (7613, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - din care, veniturile obtinute de la entitatile afiliate', 36, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'10.Venituri din alte investitii si imprumuturi care fac parte din activele imobilizate (ct. 763)', 37, N'(763, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - din care, veniturile obtinute de la entitatile afiliate', 38, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'11. Venituri din dobânzi (ct. 766)', 39, N'(766, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - din care, veniturile obtinute de la entitatile afiliate', 40, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'Alte venituri financiare (ct. 762 + 764 + 765 + 767 + 768)', 41, N'(762,c) + (764,c) + (765,c) + (767,c) + (768,c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'VENITURI FINANCIARE - TOTAL (rd. 35 + 37 + 39 + 41)', 42, N'r35 + r37 + r39 + r41')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'12. Ajustari de valoare privind imobilizarile financiare a investitiile detinute ca active circulante (rd. 44 - 45)', 43, N'r44 - r45')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - Cheltuieli (ct. 686)', 44, N'(686, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - Venituri (ct. 786)', 45, N'(786, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'13. Cheltuieli privind dobânzile (ct. 666-7418)', 46, N'(666, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'  - din care, veniturile obtinute de la entitatile afiliate', 47, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'Alte cheltuieli financiare (ct. 663 + 664 + 665 + 667+668)', 48, N'(663, d) + (664, d) + (665, d)  + (667, d) + (668, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'CHELTUIELI FINANCIARE - TOTAL (rd. 43 + 46 + 48)', 49, N'r43 + r46 +r48')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'PROFITUL SAU PIERDEREA FINANCIAR(A):', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Profit (rd. 42-49)', 50, N'max(r42 - r49, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Pierdere (rd. 49-42)', 51, N'max(r49 - r42, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'14.PROFITUL SAU PIERDEREA CURENT(A):', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Profit (rd. 10 + 42 - 32 - 49)', 52, N'max(r10 + r42 - r32 - r49, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Pierdere (rd. 32 + 49 - 10 - 42)', 53, N'MAX(r32 + r49 - r10 - r42, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'15. Venituri extraordinare (ct. 771)', 54, N'(771, c)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'16. Cheltuieli extraordinare (ct. 671)', 55, N'(671, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'17. PROFITUL SAU PIERDEREA DIN ACTIVITATEA EXTRAORDINARA', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Profit (rd. 54 - 55)', 56, N'max(r54 - r55, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Pierdere (rd. 55 - 54)', 57, N'max(r55 - r54, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'VENITURI TOTALE (rd. 10 + 42 + 54)', 58, N'r10 + r42 + r54')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'CHELTUIELI TOTALE (rd. 32 + 49 + 55)', 59, N'r32 + r49 + r55')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'PROFITUL SAU PIERDEREA BRUT(A):', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Profit (rd. 58-59)', 60, N'max(r58  - r59, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Pierdere (rd. 59-58)', 61, N'max(r59 - r58, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'18. Impozitul pe profit (ct.691)', 62, N'(691, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'19. Alte impozite nereprezentate la elementele de mai sus (ct. 698)', 63, N'(698, d)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'20. PROFITUL SAU PIERDEREA NET(A) A EXERCITIULUI FINANCIAR', 0, N'')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Profit  (rd.60-61-62-63)', 64, N'max(r60 - r61 - r62 - r63, 0)')
GO

INSERT INTO [Bilant].[c_fbpp] ([indicator], [nr], [exp])
VALUES (N'    - Pierdere (rd.61+62+63-60)', 65, N'max(r61 + r62 + r63 - r60, 0)')
GO

IF Object_id('Configurari.FormeJuridice') IS NULL
    CREATE TABLE [Configurari].[FormeJuridice] (
  [cod] numeric(2, 0)  NULL,
  [denumire] char(48) COLLATE Latin1_General_CI_AS  NULL,
  [abrev] char(10) COLLATE Latin1_General_CI_AS  NULL,
  [is_tip_soc] bit  NULL,
  [is_cif] bit  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Configurari.FormeJuridice' table  (Records 1 - 16) */

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (1, N'Societate Comerciala', N'S.C.', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (2, N'Regie Autonoma', N'R.A.', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (3, N'Companie Nationala', N'C.N.', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (4, N'Societate Nationala', N'S.N.', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (5, N'Autoritate sau Institutie Publica', N'-', 1, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (6, N'Institutie de Credit', N'-', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (7, N'Societate Cooperativa', N'S. COOP.', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (8, N'Organizatie Sindicala', N'-', 1, 1)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (9, N'Fundatie', N'-', 1, 1)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (10, N'Persoana Fizica', N'P.F.', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (11, N'Alte persoane juridice', N'-', 0, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (12, N'Organizatie patronala', N'-', 1, 1)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (13, N'Organizatie sau asociatie cu personalitate jurid', N'ORG', 0, 1)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (14, N'Persoana Fizica Autorizata', N'P.F.A.', 1, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (15, N'Asociatie Familiala', N'A.F.', 1, 0)
GO

INSERT INTO [Configurari].[FormeJuridice] ([cod], [denumire], [abrev], [is_tip_soc], [is_cif])
VALUES (16, N'Profesie exercitata in baza unor legi speciale', N'-', 1, 0)
GO

IF Object_id('Configurari.FormeOrganizare') IS NULL
    CREATE TABLE [Configurari].[FormeOrganizare] (
  [cod] numeric(2, 0)  NULL,
  [denumire] char(68) COLLATE Latin1_General_CI_AS  NULL,
  [abrev] char(20) COLLATE Latin1_General_CI_AS  NULL,
  [id_fj] numeric(2, 0)  NULL,
  [is_caen] bit  NULL
    )
    ON [PRIMARY]
GO

/* Data for the 'Configurari.FormeOrganizare' table  (Records 1 - 46) */

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (1, N'Societate In Nume Colectiv', N'S.N.C.', 1, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (2, N'Societate In Comandita Simpla', N'S.C.S.', 1, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (3, N'Societate Pe Actiuni', N'S.A.', 1, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (4, N'Societate In Comandita Pe Actiuni', N'S.C.A.', 1, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (5, N'Societate Cu Raspundere Limitata', N'S.R.L.', 1, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (11, N'Organizatie cooperatista de credit', N'-', 6, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (45, N'Banca', N'-', 6, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (46, N'Institutii emitente de moneda electronica', N'-', 6, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (47, N'Case de economii pentru domeniul locativ', N'-', 6, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (48, N'Sucursala a unei institutii de credit straina', N'-', 6, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (49, N'Alte institutii de credit', N'-', 6, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (50, N'Mestesugareasca', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (51, N'De consum', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (52, N'De valorificare', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (53, N'Agricola', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (54, N'De locuinte', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (55, N'Pescaresti', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (56, N'De transporturi', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (57, N'Forestiere', N'-', 7, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (58, N'Sindicat', N'-', 8, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (59, N'Federatie sindicala', N'-', 8, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (60, N'Confederatie sindicala', N'-', 8, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (61, N'Uniune sindicala', N'-', 8, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (62, N'Patronat', N'-', 12, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (63, N'Uniune patronala', N'-', 12, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (64, N'Federatie patronala', N'-', 12, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (65, N'Alte organizatii patronale', N'-', 12, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (66, N'Organizatie sau asociatie profesionala', N'-', 13, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (67, N'Asociatie de proprietari', N'-', 13, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (68, N'Alte organizatii sau asociatii cu personalitate juridica', N'-', 13, 1)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (78, N'Arhitect', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (79, N'Asitent medical', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (80, N'Auditor financiar', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (81, N'Avocat', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (82, N'Consilier in proprietate industriala', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (83, N'Consultant fiscal', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (84, N'Executor judecatoresc', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (85, N'Expert contabil', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (86, N'Expert vamal', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (87, N'Farmacist', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (88, N'Medic', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (89, N'Medic veterinar', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (90, N'Notar public', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (91, N'Psiholog', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (92, N'Traducator autorizat', N'-', 16, 0)
GO

INSERT INTO [Configurari].[FormeOrganizare] ([cod], [denumire], [abrev], [id_fj], [is_caen])
VALUES (93, N'Alte persoane fizice care exercita o activitate in baza unei legi sp', N'-', 16, 0)
GO

If Object_id('ComenziTransport.Consumabile') Is Null
	CREATE TABLE [ComenziTransport].[Consumabile] 
		(
		  [Id] int IDENTITY(1, 1) NOT NULL,
		  [IdMasina] int NULL,
		  [NumarMasina] varchar(10) COLLATE Latin1_General_CI_AS NULL,
		  [KmPrec] int NULL,
		  [KmBord] int NULL,
		  [DifKm] int NULL,
		  [IdTipConsumabil] int NULL,
		  [Denumire] varchar(30) COLLATE Latin1_General_CI_AS NULL,
		  [Data] date NULL,
		  [NrFactFurnizor] char(16) COLLATE Latin1_General_CI_AS NULL,
		  [Pret] money NULL,
		  [Cantitate] int NULL,
		  [Furnizor] varchar(50) COLLATE Latin1_General_CI_AS NULL,
		  [NrFactService] char(16) COLLATE Latin1_General_CI_AS NULL,
		  [PretService] money NULL,
		  [FirmaService] varchar(50) COLLATE Latin1_General_CI_AS NULL,
		  [Observatii] varchar(254) COLLATE Latin1_General_CI_AS NULL,
		  [iUserWorking] int NULL,  
		  [Created] datetime CONSTRAINT [Consumabile_Created_df] DEFAULT getdate() NOT NULL,
		  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [Consumabile_CreatedBy_df] DEFAULT suser_sname() NOT NULL,
		  [Modified] datetime CONSTRAINT [Consumabile_Modified_df] DEFAULT getdate() NOT NULL,
		  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [Consumabile_ModifiedBy_df] DEFAULT suser_sname() NOT NULL,
		  [RowVersion] int CONSTRAINT [Consumabile_RowVersion_df] DEFAULT 1 NOT NULL,
		  PRIMARY KEY CLUSTERED ([Id])
		)
		ON [PRIMARY]
GO

IF Object_id('ComenziTransport.TipuriConsumabile') IS NULL
	CREATE TABLE [ComenziTransport].[TipuriConsumabile] 
		(
		  [Id] int IDENTITY(1, 1) NOT NULL,
		  [Denumire] varchar(60) COLLATE Latin1_General_CI_AS NULL,
		  [Atentionare] bit DEFAULT 0 NULL,
		  [KilometriSchimbare] int NULL,
		  [IdCategorie] int NULL,
		  [Categorie] varchar(50) COLLATE Latin1_General_CI_AS NULL,
		  [iUserWorking] int NULL,  
		  [Created] datetime CONSTRAINT [TipuriConsumabile_Created_df] DEFAULT getdate() NOT NULL,
		  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [TipuriConsumabile_CreatedBy_df] DEFAULT suser_sname() NOT NULL,
		  [Modified] datetime CONSTRAINT [TipuriConsumabile_Modified_df] DEFAULT getdate() NOT NULL,
		  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [TipuriConsumabile_ModifiedBy_df] DEFAULT suser_sname() NOT NULL,
		  [RowVersion] int CONSTRAINT [TipuriConsumabile_RowVersion_df] DEFAULT 1 NOT NULL,
		  PRIMARY KEY CLUSTERED ([Id])
		)
	ON [PRIMARY]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'ComenziTransport' AND TABLE_NAME='ParcAuto' AND COLUMN_NAME='RovignetaInceput')
	ALTER TABLE [ComenziTransport].[ParcAuto] ADD [RovignetaInceput] date NULL, [RovignetaSfarsit] date NULL
GO

If Exists(Select * From sysobjects Where name ='pAutoAudit')
	Exec pAutoAudit 'ComenziTransport', 'Consumabile'
GO

If Exists(Select * From sysobjects Where name ='pAutoAudit')
	Exec pAutoAudit 'ComenziTransport', 'TipuriConsumabile'
GO

IF Object_id('dbo.Contracte') IS NULL
  CREATE TABLE [dbo].[Contracte] (
    [ID] int IDENTITY(1, 1) NOT NULL,
    [Cont] char(20) COLLATE Latin1_General_CI_AS NULL,
    [DenumireCli] char(60) COLLATE Latin1_General_CI_AS NULL,
    [IdTipContract] int NULL,
    [DenumireContr] char(50) COLLATE Latin1_General_CI_AS NULL,
    [Moneda] char(3) COLLATE Latin1_General_CI_AS NULL,
	[Curs] numeric(14, 4) NULL, 
    [NrContract] char(16) COLLATE Latin1_General_CI_AS NULL,
    [Data] date NULL,
    [Valoare] numeric(15, 2) NULL,
    [NrRate] numeric(3, 0) NULL,
    [Rata] numeric(15, 2) NULL,
    [DataInceput] date NULL,
    [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [DF__Contracte__Creat__13EBCCFD] DEFAULT suser_sname() NULL,
    [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [DF__Contracte__Modif__14DFF136] DEFAULT suser_sname() NULL,
    [Created] datetime CONSTRAINT [DF__Contracte__Creat__15D4156F] DEFAULT getdate() NOT NULL,
    [Modified] datetime CONSTRAINT [DF__Contracte__Modif__16C839A8] DEFAULT getdate() NULL,
    [IdUnic] int NULL,
    [iUserWorking] int NULL,
    [ZileScadenta] int NULL,
    CONSTRAINT [PK__Contract__3214EC271203848B] PRIMARY KEY CLUSTERED ([ID])
  )
  ON [PRIMARY]
GO

IF Object_id('dbo.ContracteDetaliat') IS NULL
  CREATE TABLE [dbo].[ContracteDetaliat] (
    [ID] int IDENTITY(1, 1) NOT NULL,
    [IdContract] int NULL,
    [Luna] numeric(2, 0) NULL,
    [cLuna] char(20) COLLATE Latin1_General_CI_AS NULL,
    [Anul] numeric(4, 0) NULL,
    [Valoare] numeric(15, 2) NULL,
    [ValoareFacturata] numeric(15, 2) NULL,
    [Id_Factura] int NULL,
    [NumarFactura] char(20) COLLATE Latin1_General_CI_AS NULL,
    [Data] date NULL,
    [DataScadenta] date NULL,
    [Incasat] numeric(15, 2) NULL,
    [Explicatie] char(60) COLLATE Latin1_General_CI_AS NULL,
    [NrInt] numeric(3, 0) NULL,
    CONSTRAINT [PK__Contract__3214EC273CEDE290] PRIMARY KEY CLUSTERED ([ID])
  )
  ON [PRIMARY]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Contracte' AND COLUMN_NAME='Curs')
	ALTER TABLE [dbo].[Contracte] ADD [Curs] numeric(14, 4) NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Gestiuni' AND COLUMN_NAME='Denumire')
	ALTER TABLE [dbo].[Gestiuni] ALTER COLUMN [Denumire] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Articole' AND COLUMN_NAME='DenGest')
	ALTER TABLE [dbo].[Articole] ALTER COLUMN [DenGest] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Intrari' AND COLUMN_NAME='DenGest')
	ALTER TABLE [dbo].[Intrari] ALTER COLUMN [DenGest] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='IntrariDetaliat' AND COLUMN_NAME='PretStoc')
	ALTER TABLE [dbo].[IntrariDetaliat] ALTER COLUMN [PretStoc] decimal(11, 4)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='IntrariDetaliat' AND COLUMN_NAME='Cantitate')
	ALTER TABLE [dbo].[IntrariDetaliat] ALTER COLUMN [PretStoc] decimal(12, 4)
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='IntrariDetaliat' AND COLUMN_NAME='DenGest')
	ALTER TABLE [dbo].[IntrariDetaliat] ALTER COLUMN [DenGest] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='CheltuieliVenitAvans' AND COLUMN_NAME='id_u')
	EXEC sp_rename '[dbo].[CheltuieliVenitAvans].[id_u]', 'IdUnic', 'COLUMN'
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='CheltuieliVenitAvans' AND COLUMN_NAME='IdUnic')
	ALTER TABLE [dbo].[CheltuieliVenitAvans] ALTER COLUMN [IdUnic] int
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='PreluareStocuri' AND COLUMN_NAME='DenGest')
	ALTER TABLE [dbo].[PreluareStocuri] ALTER COLUMN [DenGest] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='PreluareStocuri' AND COLUMN_NAME='DenTipArt')
	ALTER TABLE [dbo].[PreluareStocuri] ALTER COLUMN [DenTipArt] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='PreluareStocuri' AND COLUMN_NAME='TipDoc' AND COLUMN_DEFAULT IS NULL)
	ALTER TABLE [dbo].[PreluareStocuri] ADD DEFAULT 'II' FOR [TipDoc]
GO

EXEC dbo.pDropDefaultConstraintAndColumn [dbo], [PreluareStocuri], [Tip]
GO

If Exists(Select * From sysobjects Where name ='DelMiscari')
  Drop Procedure [DelMiscari]	
GO

Create Procedure DelMiscari
		@pIdDels int, --IdUnicFactura
		@lOk bit OUTPUT
As
	/**********************************************************
	  Creation Date:  26/12/2010
	Creation Author:  Vicos
			Purpose:  Sterge din ItemsTransactions si ItemsDischarge
					  toate miscarile pentru Documentul identificat prin IdUnic			
			  NOTE:  
	Local Variables:
		  Called By: 
			  Calls:
	***********************************************************/
Begin Transaction
	Declare @Id int 
	Declare @IdUnic int
	Declare @IdDoc int
	Declare @Data datetime 
	Declare @IdArticol int 
	Declare @IdGest int 
	Declare @Cantitate decimal(12, 4)
	Declare @CantitateRamasa decimal(12, 4) 
	Declare @Pret decimal(10, 4) 
	Declare @TipDocument char(10)
	Declare @NumarDoc char(16) 
	Declare @SumaDescarcata numeric(14, 4)
	Declare @PlanB char(16) 
	Declare @CapitolB char(16) 
	Declare @ArticolB char(16) 
	Declare @IdCategorie int 
	Declare @IdLot int     
	Declare @MyIdDescarcare int
	Declare Miscari Cursor Local For Select * From ItemsTransactions Where IdDoc = @pIdDels
	Open Miscari
	Fetch Next From Miscari
	Into @Id, @IdUnic, @IdDoc, @Data, @IdArticol, @IdGest, @Cantitate, @CantitateRamasa, @Pret, @TipDocument, @NumarDoc, @SumaDescarcata, @PlanB, @CapitolB, @ArticolB, @IdCategorie, @IdLot
	Declare @lb_Exit  bit
	Set @lb_Exit  = 0
	While @@FETCH_STATUS = 0 And (@lb_Exit = 0) 
	Begin
		If dbo.VerificInchidereGestiune(@Data) = 0 Set @lb_Exit  = 1
			Update Articole Set Stoc = Stoc-@Cantitate Where Id=@IdArticol		
			Delete From ItemsTransactions Where Id = @Id
			If @Cantitate < 0
				Begin
					Update ItemsTransactions
						Set CantitateRamasa = CantitateRamasa + d.Cantitate
                      From ItemsTransactions i
                      	Inner Join ItemsDischarge d On 
                        	i.IdUnic = d.IdUDesc 
                            And i.Id = d.IdDesc
                            And i.IdArticol = d.IdArticol
                            And i.IdGest = d.IdGest
                            And i.IdArticol = @IdArticol
                            And i.IdGest = @IdGest
                            And d.IdNew = @IdDoc
                            And d.IdUNew = @idUnic
					Delete From ItemsDischarge 
                       	Where 
                           	IdNew=@pIdDels
                               And IdArticol=@IdArticol 
                               And IdGest=@IdGest; 
				End
		Fetch Next From Miscari
		Into @Id, @IdUnic, @IdDoc, @Data, @IdArticol, @IdGest, @Cantitate, @CantitateRamasa, @Pret, @TipDocument, @NumarDoc, @SumaDescarcata, @PlanB, @CapitolB, @ArticolB, @IdCategorie, @IdLot
	End
	Close Miscari
	Deallocate Miscari
If @@Error<>0
	Begin
		Execute [dbo].[uspPrintError];
        If XACT_STATE() <> 0 RollBack Transaction;
		Execute [dbo].[uspLogError];
		Set @lOk =  0
	End  
Else
	Begin
	  Commit Transaction
	  Set @lOk = 1
   End
Return @lOk
GO

If Object_Id('GetStoc') Is Not Null
  Drop Function [GetStoc]
GO

Create Function dbo.GetStoc ( @nIdArticol Int, @nIdGest Int, @dDataDoc Date ) 
Returns Decimal(13, 3) 
As
Begin
  Declare @Stoc Decimal(13, 3) = 0
  If IsNull(@nIdGest, 0)<>0 -- o Gestiune
      Begin
        Set @Stoc = 
          (Select Sum(Cantitate) 
          From ItemsTransactions 
              Where 
                  IdArticol = @nIdArticol 
                  And Data <= @dDataDoc 
                  And IdGest = @nIdGest
              Group By IdArticol, IdGest
          )  
      End
  If IsNull(@nIdGest, 0)=0 -- Toate Gestiunile
      Begin
        Set @Stoc = 
          (
          Select Sum(Cantitate) 
          From ItemsTransactions 
              Where 
                  IdArticol = @nIdArticol 
                  And Data <= @dDataDoc 
          Group By IdArticol
          )     
      End 
	Return IsNull(@Stoc, 0)
End
GO

If Object_Id('ExtractInteger') Is Not Null
  Drop Function [ExtractInteger]
GO

CREATE Function ExtractInteger(@String VarChar(254))
Returns VarChar(254)
As
Begin
	Declare @Count Int
	Declare @IntNumbers VarChar(254)
	Set @Count = 0
	Set @IntNumbers = ''
	While @Count <= Len(@String)
	Begin
		If SubString(@String, @Count, 1) >= '0' And SubString(@String, @Count, 1) <= '9'
        Begin
			Set @IntNumbers = @IntNumbers + SubString(@String, @Count, 1)
		End
		Set @Count = @Count + 1
	End
	Return @IntNumbers
End
GO

-- Adaugare Coloana CreatedBy sau modifica Coloana CreatedBy din Int in nVarChar
Set NoCount On
Declare
   @TableName SysName, 
   @SchemaName SysName, 
   @SQL nVarChar(max)
-- for each table
-- 1
Declare  cTables Cursor FAST_FORWARD READ_ONLY For
	Select s.name, t.name 
	From sys.tables t
		Join sys.schemas s On t.schema_id = s.schema_id
		Where t.name Not In
             	('Audit', 'ItemsTransactions', 'ItemsDischarge', 'Caen', 'Clase', 
                'ImpozitMinim', 'Tranzactii', 'Trezorerie', 
                'FiscalYears', 'Zone', 'Adrese', 'Bic', 'Version',
                'Tva',  'WarningLevels', 
                'F101', 'D100', 'D101', 'D103', 'D300', 'D300_DecontTva', 'D390', 'D394', 'D394_Cumparari', 'D394_Vanzari',
                'PROD_MeasureUnitsClasses', 'PROD_MeasureUnits', 'PROD_PropertyItems', 'PROD_PropertyItemValues', 'PROD_PropertyClasses', 
                'DocTypeDirections', 'DocNumeration', 'DocTypes', 'DocTypeBase', 'DocTypeDirections', 'DocType', 'DocumentBase', 'EntityTypes',
                'NumerotareDocumente', 'Nationalitati', 
                'BanciTerti', 'Categorii', 'SystemParameters', 'Sucursale',
                'ErrorLog', 'xml', 'Numerators', 'SchemaAudit' )
--2 
Open cTables
--3 
Fetch cTables Into @SchemaName, @TableName   -- prime the cursor
While @@Fetch_Status = 0 
	Begin
	If Not Exists 
				(
				Select *
				From sys.tables t
					Join sys.schemas s On s.schema_id = t.schema_id
					Join sys.columns c On t.object_id = c.object_id
					Where  t.name = @TableName And s.name = @SchemaName And c.name = 'CreatedBy'
				)
		Begin                                                                                      
			Set @SQL = 'Alter Table [' + @SchemaName + '].[' + @TableName + '] Add CreatedBy nVarChar(128) Not Null Constraint ' + @TableName + '_CreatedBy_df Default(Suser_SName())'
		Exec (@SQL)
		End
	Else
		Begin                                                                                           
			Set @SQL = 'Alter Table  [' + @SchemaName + '].[' + @TableName + '] Alter Column  CreatedBy nVarChar(128) '
		-- NOT NULL constraint ' + @TableName + '_CreatedBy_df Default(Suser_SName())'
		Exec (@SQL)
		End
	Fetch cTables Into @SchemaName, @TableName   -- fetch next
End
-- 4  
Close cTables
-- 5
Deallocate  cTables
-----------------------------------------------------------------------
GO

-- Blocare Conturi Standard presupune ca inregistrarile din Clona_Firma.dbo.Conturi sa aiba Blocat =1
Merge Into Conturi c
Using Clona_Firma.dbo.Conturi cc On c.Cont = cc.Cont
When Matched
	Then Update Set Blocat = 1;
GO

IF Object_id('ComenziTransport.Cheltuieli') IS NULL
CREATE TABLE [ComenziTransport].[Cheltuieli] (
  [Id] int IDENTITY(1, 1) NOT NULL,
  [IdComenzi] int NOT NULL,
  [Denumire] varchar(100) COLLATE Latin1_General_CI_AS NULL,
  [Data] date NULL,
  [CodValuta] char(3) COLLATE Latin1_General_CI_AS NULL,
  [Curs] numeric(14, 4) NULL,
  [SumaValuta] numeric(14, 2) NULL,
  [Suma] numeric(14, 2) NULL,
  [iUserWorking] int NULL,
  [Created] datetime CONSTRAINT [Cheltuieli_Created_df] DEFAULT getdate() NOT NULL,
  [Modified] datetime CONSTRAINT [Cheltuieli_Modified_df] DEFAULT getdate() NOT NULL,
  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [Cheltuieli_CreatedBy_df] DEFAULT suser_sname() NULL,
  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS CONSTRAINT [Cheltuieli_ModifiedBy_df] DEFAULT suser_sname() NULL,
  [RowVersion] int CONSTRAINT [Cheltuieli_RowVersion_df] DEFAULT 1 NOT NULL,
  UNIQUE ([Id])
)
ON [PRIMARY]
GO

IF Object_id('dbo.ContracteTip') IS NULL
CREATE TABLE [dbo].[ContracteTip] (
  [Id] int IDENTITY(1, 1) NOT NULL,
  [Denumire] char(50) COLLATE Latin1_General_CI_AS NULL,
  [ContCredit] char(20) COLLATE Latin1_General_CI_AS NULL,
  [IdCategorie] int NULL,
  [Categorie] varchar(60) COLLATE Latin1_General_CI_AS NULL,
  [Explicatie] varchar(100) COLLATE Latin1_General_CI_AS NULL,
  [CreatedBy] nvarchar(128) COLLATE Latin1_General_CI_AS DEFAULT suser_sname() NULL,
  [ModifiedBy] nvarchar(128) COLLATE Latin1_General_CI_AS DEFAULT suser_sname() NULL,
  [Created] datetime DEFAULT getdate() NULL,
  [Modified] datetime DEFAULT getdate() NULL,
  [iUserWorking] int NULL,
  PRIMARY KEY CLUSTERED ([Id])
)
ON [PRIMARY]
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='MijloaceFixe' AND COLUMN_NAME='Id_Fact_Ies')
	ALTER TABLE [dbo].[MijloaceFixe]ADD [Id_Fact_Ies] int NULL
GO

IF Not EXISTS ( SELECT t.name AS [Table Name], ex.value AS Description 
				FROM sys.tables AS t, sys.extended_properties AS ex
				WHERE 
					ex.major_id = t.object_id 
					AND ex.name = 'MS_Description' 
					AND t.Name = 'MijloaceFixe' 
					AND Value  = 'IdUnic din Iesiri Antet')
                    
EXEC sp_addextendedproperty 'MS_Description', N'IdUnic din Iesiri Antet', 'schema', 'dbo', 'table', 'MijloaceFixe', 'column', 'Id_Fact_Ies'
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B1Ies')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B1Ies] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B2Ies')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B2Ies] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B3Ies')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B3Ies] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B4Ies')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B4Ies] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B1Exp')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B1Exp] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B2Exp')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B2Exp] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B3Exp')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B3Exp] char(20) NULL
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='ConfigurareConturi' AND COLUMN_NAME='Fa_B4Exp')
	ALTER TABLE [Configurari].[ConfigurareConturi] ADD [Fa_B4Exp] char(20) NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Import' AND COLUMN_NAME='ContAlteTaxe')
	ALTER TABLE [dbo].[Import] ALTER COLUMN [ContAlteTaxe] varchar(20) COLLATE Latin1_General_CI_AS
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Dbo' AND TABLE_NAME='Dpi' AND COLUMN_NAME='Cont')
	ALTER TABLE [dbo].[Dpi] ADD [Cont] char(20) NULL
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Configurari' AND TABLE_NAME='Semnaturi' AND COLUMN_NAME='DenumireRaport')
	ALTER TABLE [Configurari].[Semnaturi] ALTER COLUMN [DenumireRaport] varchar(60) COLLATE Latin1_General_CI_AS
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Salarii' AND TABLE_NAME='COR' AND COLUMN_NAME='ParentCor')
	ALTER TABLE [Salarii].[COR] ALTER COLUMN [ParentCor] int
GO

/********************************************/
/*Update#20111001.sql*/
GO

IF Object_id('DF_Version_iVersion') IS NOT NULL
	ALTER TABLE [dbo].[Version] DROP CONSTRAINT [DF_Version_iVersion]
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Version' AND COLUMN_NAME='iVersion' AND COLUMN_DEFAULT IS NULL)
	ALTER TABLE [dbo].[Version] ADD DEFAULT 0 FOR [iVersion]
GO

--IF Object_id('DF_Version_iVersionC') IS NOT NULL
--	ALTER TABLE [dbo].[Version] DROP CONSTRAINT [DF_Version_iVersionC]
--GO

--IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Version' AND COLUMN_NAME='iVersionC' AND COLUMN_DEFAULT IS NULL)
--	ALTER TABLE [dbo].[Version] ADD DEFAULT 0 FOR [iVersionC]
--GO

If Object_Id('GetNextOP') Is Not Null
  Drop Function [GetNextOP]
GO

Create Function GetNextOP (@pCont Char(20))
Returns Char(20)
As
Begin
     Return
        (
         Select Max(IsNull(dbo.GetNumberFromString(Ndp), 0)) + 1 As Ndp
            From Registru
               Where Left(ContC,4) = @pCont
                     And Left(ContD, 1) = '4' 
                     And Ndp Not Like '%E%' 
         )
End
GO

--exec master.dbo.sp_configure N'query governor cost limit', N'1200';
Exec Sp_Configure 'Show Advanced Options', 1 RECONFIGURE
Exec Sp_Configure 'query governor cost limit', 0 RECONFIGURE
Exec Sp_Configure 'Show Advanced Options', 0 RECONFIGURE
GO

If Lower(Db_Name())='scpromexcomsrl' Or Lower(Db_Name())='stanimir'
Begin
Truncate Table Configurari.Semnaturi
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Nir', N'Nir(Adaos)', NULL, NULL, NULL, 1, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'DispozitiiPlataIncasare', N'Dispozitii Plata/Incasare', NULL, NULL, NULL, 1, 1, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Salarii', N'Salarii', N'', N'', NULL, 1, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'RaportZilnic', N'Raport de Gestiune zilnic', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'jCump', N'Jurnale Tva', NULL, NULL, NULL, 1, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Registru_Inv', N'Registru Inventar', NULL, NULL, NULL, 1, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Impozit', N'Fisa calcul impozit profit', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Reg', N'Registru Jurnal', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Casa_Nt', N'Nota de transfer numerar', NULL, NULL, NULL, 1, 1, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Nc', N'Nota Contabila', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Nir_Pvr', N'Proces Verbal de Receptie Imobilizari', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Registru1', N'Solduri Initiale / Rulaje Precedente', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'RegistruCasa', N'Registru de Casa', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Stoc_Bc', N'Bonuri Consum', NULL, NULL, NULL, 1, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Voucher', N'Jurnal Voucher', NULL, NULL, NULL, 0, 0, NULL, N'sa', N'sa')
INSERT INTO [Configurari].[Semnaturi] ([Raport], [DenumireRaport], [s1], [s2], [s3], [Is2], [Is3], [iUserWorking], [CreatedBy], [ModifiedBy])
VALUES (N'Bal3', N'Balanta Contabila', NULL, NULL, NULL, 1, 0, NULL, N'sa', N'sa')
End
GO

/********************************************/
/*Update#20111012.sql*/
GO


IF Object_id('Declaratii.Op') IS NULL
CREATE TABLE [Declaratii].[Op] (
  [Id] int IDENTITY(1, 1) NOT NULL,
  [Tip] char(2) COLLATE Latin1_General_CI_AS NULL,
  [Platitor] char(60) COLLATE Latin1_General_CI_AS NULL,
  [NumeBancaPlatitor] char(60) COLLATE Latin1_General_CI_AS NULL,
  [FilialaPlatitor] char(60) COLLATE Latin1_General_CI_AS NULL,
  [IbanPlatitor] char(24) COLLATE Latin1_General_CI_AS NULL,
  [BicPlatitor] char(8) COLLATE Latin1_General_CI_AS NULL,
  [Beneficiar] char(60) COLLATE Latin1_General_CI_AS NULL,
  [NumeBancaBen] char(60) COLLATE Latin1_General_CI_AS NULL,
  [FilialaBancaBeneficiar] char(60) COLLATE Latin1_General_CI_AS NULL,
  [IbanBeneficiar] char(24) COLLATE Latin1_General_CI_AS NULL,
  [BicBeneficiar] char(8) COLLATE Latin1_General_CI_AS NULL,
  [TipCodBare] bit NULL,
  [NumarDoc] char(12) COLLATE Latin1_General_CI_AS NULL,
  [DataDoc] date NULL,
  [Suma] numeric(12, 2) NULL,
  [SoldFinal] numeric(12, 2) NULL,
  [SumaInitiala] numeric(12, 2) NULL,
  [Explicatie] varchar(100) COLLATE Latin1_General_CI_AS NULL,
  [NrEvidenta] char(23) COLLATE Latin1_General_CI_AS NULL,
  [CodBugetar] char(20) COLLATE Latin1_General_CI_AS NULL,
  CONSTRAINT [Op_pk] PRIMARY KEY CLUSTERED ([Id])
)
ON [PRIMARY]
GO

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

/*Update#20111013.sql*/
GO

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'Declaratii' AND TABLE_NAME='Op' AND COLUMN_NAME='NrEvidenta')
	ALTER TABLE [Declaratii].[Op] ALTER COLUMN [NrEvidenta] char(23) COLLATE Latin1_General_CI_AS
GO

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

/*Update#20111014.sql*/
GO


Truncate TABLE [Declaratii].[D300_DecontTva]
GO

/* Data for the 'Declaratii.D300_DecontTva' table  (Records 1 - 48) */

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4427', N'1', N'Livrari intracomunitare de bunuri, scutite cf.art.143 alin.(2) lit.a) si d) din Codul Fiscal', 1, 0, N'14', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'2', N'Regularizari livrari intracomunitare scutite conform art.143 alin.(2)  lit.a) si d) din Codul Fiscal', 1, 0, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'3', N'Livrari de bunuri sau prestari de servicii pentru care locul livrarii/ locul prestarii este in afara Romaniei (in UE sau in afara UE), precum si livrari intracomunitare de bunuri, scutite cf.art.143 alin.(2) lit.b) si c) din Codul Fiscal, din care:', 1, 0, N'12', N'13', N'15', NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'3.1', N'Prestari de servicii intracomunitare care nu beneficiaza de scutire in statul membru in care taxa este datorata', 1, 0, NULL, NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'4', N'Regularizari privind prestarile de servicii intracomunitare care nu beneficieaza de scutire in statul membru in care este datorata', 1, 0, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'5', N'Achizitii intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa) din care:', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'5.1', N'Achizitii intracomunitare pentru care cumparatorul este obligat la plata TVA (taxare inversa), iar furnizorul este inregistrat in scopuri de TVA in statul membru din care a avut loc livrarea intracomunitara', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'6', N'Regularizari privind achizitii intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'7', N'ACHIZITII de bunuri, altele decat cele de la rd.4 si rd.5, si achizitii de servicii pentru care beneficiarul din Romania este obligat la plata TVA (taxare inversa), din care', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'7.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa) din care:', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'7.1.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa), iar prestatorul este inregistrat in scopuri de TVA in statul membru din care efectueaza prestarea de servicii', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'8', N'Regularizari privind achizitiile de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'9', N'LIVRARI de bunuri si prestari de servicii, taxabile cu cota 24%', 1, 1, N'6-7', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'10', N'LIVRARI de bunuri si prestari de servicii, taxabile cu cota  9%', 1, 1, N'8-9', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'11', N'LIVRARI de bunuri taxabile cu cota 5%', 1, 1, N'19-20', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'12', N'ACHIZITII de bunuri si servicii achizitionate supuse masurilor de simplificare pentru care beneficiarul este obligat la plata TVA (taxare inversa)', 1, 1, N'17-18', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'13', N'LIVRARI de bunuri si prestari de servicii scutite cu drept de deducere, cu exceptia celor de la rd.1-3, si operatiuni supuse masurilor de simplificare', 1, 0, N'16', N'10', N'11', N'18', NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'14', N'LIVRARI de bunuri si prestari de servicii scutite fara drept de deducere', 1, 0, N'17', NULL, NULL, NULL, NULL, 2)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'15', N'Regularizari taxa colectata', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'16', N'TOTAL TAXA COLECTATA   (rd. 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4426', N'17', N'ACHIZITII intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa), din care:', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'17.1', N'Achizitii intracomunitare pentru care cumparatorul este obligat la plata TVA (taxare inversa), iar furnizorul este inregistrat in scopuri de TVA in statul membru din care a avut loc livrarea', 1, 1, N'11-12', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'18', N'Regularizari privind achizitii intracomunitare de bunuri pentru care cumparatorul este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'19', N'ACHIZITII de bunuri , altele decat cele de la rd.17 si 18, si achizitii de servicii achizitionate pentru beneficiarul din Romania este obligat la plata TVA (taxare inversa), din care:', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'19.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa), din care:', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'19.1.1', N'Achizitii de servicii intracomunitare pentru care beneficiarul este obligat la plata TVA (taxare inversa), iar prestatorul este inregistrat in scopuri de TVA in statul memebru din care efectueaza prestarea de servicii', 1, 1, N'15-16', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'20', N'Regularizarile privind achizitiile de servicii intracomunitare pentru care beneficiarul din Romania este obligat la plata TVA (taxare inversa)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'21', N'Achizitii de bunuri si servicii taxabile cu cota de 24%', 1, 1, N'6-7', N'17-18', NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'22', N'Achizitii de bunuri si servicii taxabile cu cota de  9%', 1, 1, N'8-9', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'23', N'Achizitii de bunuri taxabile cu cota de  5%', 1, 1, N'19-20', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'24', N'Achizitii de bunuri si servicii scutite de taxa sau neimpozabile, din care:', 1, 0, N'10', N'13', N'14', NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'24.1', N'Achizitii de servicii intracomunitare scutite de taxa', 1, 0, N'13', NULL, NULL, NULL, NULL, 1)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'25', N'TOTAL TAXA DEDUCTIBILA (rd.17+18+19+20+21+22+23)', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'26', N'SUB-TOTAL TAXA DEDUSA CONFORM ART.145  si 145^1 SAU 147 si 147^1', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'27', N'TVA efectiv restituita cumparatorilor straini, inclusiv comisionul unitatilor autorizate', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'28', N'Regularizari taxa dedusa', 1, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'29', N'Ajustari la finele anului conform pro-rata/ ajustari pentru bunurile de capital', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'30', N'TOTAL TAXA DEDUSA (rd.26+27+28+29)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4424', N'31', N'Suma negativa a TVA in perioada de raportare (rd.30 - rd.16)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4423', N'32', N'Taxa de plata in perioada de raportare (rd.16 - rd.30)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4423', N'33', N'Soldul TVA de plata din decontul perioadei fiscale precedente (rd.39 din decontul perioadei fiscale precedente) neachitata pana la data depunerii decontului de TVA', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'34', N'Diferente de TVA de plata stabilite de organele de inspectie fiscala prin decizie comunicata si neachitate pana la data depunerii decontului de TVA', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'35', N'TVA de plata cumulat (rd.32+rd.33+rd.34)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4424', N'36', N'Soldul sumei negative a TVA reportata din perioada fiscala precedenta pentru care nu s-a solicitat rambursare (rd.40 din decontul perioadei fiscale precedente)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'37', N'Diferente negative de TVA stabilite de organele de inspectie fiscala prin decizie comunicata pana la data depunerii decontului de TVA', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (NULL, N'38', N'Suma negativa a TVA cumulate (rd.31+rd.36+rd.37)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4423', N'39', N'Sold TVA de plata la sfarsitul perioadei de raportare (rd.35-rd.38)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

INSERT INTO [Declaratii].[D300_DecontTva] ([Cont], [Rand], [Denumire], [Is_Col1], [Is_Col2], [Cod1], [Cod2], [Cod3], [Cod4], [Cod5], [Jurnal])
VALUES (N'4424', N'40', N'Soldul sumei negative de TVA la sfarsitul perioadei de raportare (rd.38-rd.35)', 0, 1, NULL, NULL, NULL, NULL, NULL, 0)
GO

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

/*Update#20111020.sql*/
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME='Contracte' AND COLUMN_NAME='SfContract')
	ALTER TABLE [dbo].[Contracte] ADD [SfContract] bit DEFAULT 0 NULL
GO

Select * From Configurari.SystemParameters Where sKey = 'lShowDeletedInvoice'
If @@ROWCOUNT = 0
	INSERT INTO [Configurari].[SystemParameters] ([sKey], [sDescription], [sValue], [sDefaultValue], [iUserWorking], [Blocat], [modul], [AcceptValue], [IsHidden], [IsReadOnly])
	VALUES (N'lShowDeletedInvoice', N'Afisare Facturi de Iesire Anulate', N'Da', N'Da', NULL, 1, NULL, N'Da#Nu', 0, 1)
GO


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

/*Update#20111022.sql*/
GO


If Object_Id('GetNextOP') Is Not Null
  Drop Function [GetNextOP]
GO

Create Function GetNextOP (@pCont Char(20))
Returns Char(20)
As
Begin
     Return
        (
         Select Max(IsNull(dbo.GetNumberFromString(Ndp), 0)) + 1 As Ndp
            From Registru
               Where ContC = @pCont
                     And Left(ContD, 1) = '4' 
                     And Ndp Not Like '%E%' 
         )
End
GO

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

/*Update#20111026.sql*/
GO

If Object_Id('GetLastNumberIesiriByTipDoc') Is Not Null
  Drop Function [GetLastNumberIesiriByTipDoc]
GO

Create Function dbo.GetLastNumberIesiriByTipDoc ( @TipDoc Char(1) )
Returns Char(16)
As
Begin
	Return  
    	(
		Select Max(IsNull(dbo.GetNumberFromString(NumarDoc), 0)) As NumarDoc
    	From Iesiri 
        	Where 
				Case
					When IsNull(@TipDoc, '') = '' And Tip In ('', 'R') Then 1           
					When IsNull(@TipDoc, '') <> '' And Tip = @TipDoc Then 1
					Else 0
				End = 1
            And IsNull(Anulat, 0) = 0
            )
End
GO

If Object_Id('GetLastNumberExportByTipDoc') Is Not Null
  Drop Function [GetLastNumberExportByTipDoc]
GO

Create Function dbo.GetLastNumberExportByTipDoc ( @TipDoc Char(1) )
Returns Char(16)
As
Begin
	Return  
    	(
		Select Max(IsNull(dbo.GetNumberFromString(NumarDoc), 0)) As NumarDoc
    	From Export With (UpdLock, HoldLock)
        	Where Upper(Tip) = Upper(@TipDoc)
		)
     
End
GO

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