INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (207, NULL, N'Joe', N'', N'Four', NULL, CAST(N'2002-02-02T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T21:05:26.333' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (208, NULL, N'Peter', N'', N'Ally', NULL, CAST(N'2012-01-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T14:27:31.950' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (209, NULL, N'Frank', N'', N'Schmidt', NULL, CAST(N'1982-01-02T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T14:27:41.023' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (210, NULL, N'Liam', N'', N'Thomas', NULL, CAST(N'1982-02-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T21:43:21.280' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (211, N'', N'Snark', N'', N'Plen', N'', CAST(N'1982-01-02T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-04-28T21:49:03.610' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (212, NULL, N'Frank', N'', N'Spank', NULL, CAST(N'2001-01-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T21:51:06.090' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (213, NULL, N'Blayne', N'', N'Blaze', NULL, CAST(N'1920-02-19T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T14:16:58.017' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (214, NULL, N'Frankie', N'', N'Smith', NULL, CAST(N'2010-01-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T22:18:26.253' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (215, NULL, N'Anudder', N'', N'Test', NULL, CAST(N'1982-02-02T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T13:58:02.867' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (216, N'', N'Peter', N'', N'Allison', N'', CAST(N'1923-01-02T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-04-28T22:28:34.733' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (217, NULL, N'Johnny', N'', N'Allison', NULL, CAST(N'2004-02-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T22:29:11.230' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (218, NULL, N'Sue', N'', N'Anerror', NULL, CAST(N'2008-04-05T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T22:32:14.317' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (219, N'Dr', N'Sandy', N'', N'Plaint', NULL, CAST(N'1980-07-14T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T22:43:25.123' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (220, NULL, N'Hardee', N'', N'Johns', NULL, CAST(N'1995-11-23T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T23:07:51.380' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (221, NULL, N'Yikes', N'', N'ALlen', NULL, CAST(N'2010-01-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T00:52:31.170' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (222, N'', N'Party', N'', N'Donne', N'', CAST(N'1982-02-02T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-04-28T23:52:27.883' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (223, NULL, N'Lil', N'', N'Donne', NULL, CAST(N'2002-02-02T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-28T23:52:49.310' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (224, NULL, N'Peter', N'', N'Pan', NULL, CAST(N'1927-02-18T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T09:15:47.087' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (225, NULL, N'Tinker', N'', N'Bell', NULL, CAST(N'1843-09-23T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T09:21:59.387' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (226, NULL, N'Hook', N'', N'Pirate', NULL, CAST(N'1909-04-19T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T09:26:04.937' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (227, NULL, N'Croc', N'', N'Odile', NULL, CAST(N'1850-09-20T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T09:27:30.400' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (228, NULL, N'Al', N'', N'Ligator', NULL, CAST(N'1928-08-09T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T12:11:32.317' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (229, NULL, N'Bol', N'', N'Oogna', NULL, CAST(N'1985-07-08T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T14:16:42.333' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (230, NULL, N'Graham', N'', N'Key', NULL, CAST(N'1854-01-14T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T13:27:18.880' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (231, N'', N'Fred', N'', N'Flintstone', N'', CAST(N'1834-05-01T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-04-29T14:29:49.677' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (232, NULL, N'Newton', N'', N'Client', NULL, CAST(N'2011-01-01T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-04-29T14:30:09.850' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (233, N'', N'arnold', N'', N'Hames', N'', CAST(N'1956-11-06T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-05-02T20:29:17.040' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (234, N'', N'billy', N'', N'joe', N'', CAST(N'2000-01-01T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-05-02T20:32:06.800' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (235, N'', N'bernard', N'', N'johnston', N'', CAST(N'2000-01-01T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-05-12T08:04:53.260' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (236, N'', N'Kelly', N'', N'Mistral', N'', CAST(N'2011-01-01T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-05-11T13:19:11.043' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (237, N'', N'John', N'', N'Wayne', N'', CAST(N'1920-02-02T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-05-17T12:58:30.757' AS DateTime), N'gsavard', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (238, N'', N'Abe', N'', N'Lincoln', N'', CAST(N'2000-01-01T00:00:00.000' AS DateTime), N'', 0, CAST(N'2011-05-18T16:44:48.047' AS DateTime), N'DanJohnston', 0)
INSERT [Person].[Person] ([PersonID], [Title], [FirstName], [MiddleName], [LastName], [Suffix], [DateOfBirth], [EmailAddress], [EmailContactPreference], [ModifiedDate], [ModifiedBy], [IsDeleted]) VALUES (244, N'', N'Bugs', N'', N'Jonsten', N'', CAST(N'2000-06-09T00:00:00.000' AS DateTime), NULL, 0, CAST(N'2011-06-20T15:01:03.183' AS DateTime), N'SSE', 0)
SET IDENTITY_INSERT [Person].[Person] OFF
SET IDENTITY_INSERT [Person].[Phone] ON 

INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (46, 186, N'8028994164', N'', 1, CAST(N'2011-05-19T13:47:20.840' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (47, 186, N'8029999657', N'', 3, CAST(N'2011-05-19T13:47:20.840' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (48, 193, N'', N'', 1, CAST(N'2011-05-16T09:37:15.810' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (49, 193, N'', N'', 3, CAST(N'2011-05-16T09:37:15.810' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (50, 194, N'', N'', 1, CAST(N'2011-04-20T09:36:01.037' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (51, 194, N'', N'', 3, CAST(N'2011-04-20T09:36:01.037' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (52, 195, N'', N'', 1, CAST(N'2011-04-20T09:37:12.723' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (53, 195, N'', N'', 3, CAST(N'2011-04-20T09:37:12.723' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (54, 235, N'', N'', 1, CAST(N'2011-05-12T08:04:53.260' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (55, 235, N'', N'', 3, CAST(N'2011-05-12T08:04:53.260' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (56, 236, N'', N'', 1, CAST(N'2011-05-11T13:19:11.043' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (57, 236, N'', N'', 3, CAST(N'2011-05-11T13:19:11.043' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (58, 192, N'', N'', 1, CAST(N'2011-05-17T12:56:44.837' AS DateTime), N'gsavard')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (59, 192, N'', N'', 3, CAST(N'2011-05-17T12:56:44.837' AS DateTime), N'gsavard')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (60, 237, N'9996667777', N'', 1, CAST(N'2011-05-17T12:58:30.757' AS DateTime), N'gsavard')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (61, 238, N'', N'', 1, CAST(N'2011-05-18T16:44:48.050' AS DateTime), N'DanJohnston')
INSERT [Person].[Phone] ([PhoneID], [PersonID], [PhoneNumber], [PhoneExtension], [PhoneType], [ModifiedDate], [ModifiedBy]) VALUES (62, 238, N'', N'', 3, CAST(N'2011-05-18T16:44:48.050' AS DateTime), N'DanJohnston')
SET IDENTITY_INSERT [Person].[Phone] OFF
SET IDENTITY_INSERT [SSN].[SSN] ON 

INSERT [SSN].[SSN] ([SSNID], [PersonID], [SSN], [ModifiedDate], [ModifiedBy]) VALUES (1, 1, N'009117788', CAST(N'2010-10-25T18:04:06.170' AS DateTime), N'SSE')
SET IDENTITY_INSERT [SSN].[SSN] OFF
/****** Object:  Index [UK_FoodShelfCertification]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Foodshelf].[FoodShelfCertification] ADD  CONSTRAINT [UK_FoodShelfCertification] UNIQUE NONCLUSTERED 
(
	[FoodShelfCertificationID] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_FoodTypeGiven]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Foodshelf].[FoodTypeGiven] ADD  CONSTRAINT [UK_FoodTypeGiven] UNIQUE NONCLUSTERED 
(
	[FoodTypeGivenID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_FoodTypeGivenRecord]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Foodshelf].[FoodTypeGiven] ADD  CONSTRAINT [UK_FoodTypeGivenRecord] UNIQUE NONCLUSTERED 
(
	[FoodTypeGivenID] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_Signature]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Foodshelf].[Signature] ADD  CONSTRAINT [UK_Signature] UNIQUE NONCLUSTERED 
(
	[SignatureID] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_FamilyRelationships]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Person].[FamilyRelationships] ADD  CONSTRAINT [UK_FamilyRelationships] UNIQUE NONCLUSTERED 
(
	[ClientPersonID] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_IncomeSource]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Person].[Income] ADD  CONSTRAINT [UK_IncomeSource] UNIQUE NONCLUSTERED 
(
	[IncomeSourceRowID] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_LUCounty]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Person].[LUCounty] ADD  CONSTRAINT [UK_LUCounty] UNIQUE NONCLUSTERED 
(
	[CountyID] ASC,
	[CityID] ASC,
	[StateID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [PK_ProgramService]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Person].[ProgramServicesUsed] ADD  CONSTRAINT [PK_ProgramService] UNIQUE NONCLUSTERED 
(
	[ServiceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_ProgramServicesUsed]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Person].[ProgramServicesUsed] ADD  CONSTRAINT [UK_ProgramServicesUsed] UNIQUE NONCLUSTERED 
(
	[ServiceID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_Signature]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Signature].[Signature] ADD  CONSTRAINT [UK_Signature] UNIQUE NONCLUSTERED 
(
	[SignatureID] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [UK_Signatures]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [Signature].[Signatures] ADD  CONSTRAINT [UK_Signatures] UNIQUE NONCLUSTERED 
(
	[SignaturesID] ASC,
	[PersonID] ASC,
	[SignatureID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [UK_SSN]    Script Date: 1/6/2018 9:07:44 PM ******/
ALTER TABLE [SSN].[SSN] ADD  CONSTRAINT [UK_SSN] UNIQUE NONCLUSTERED 
(
	[SSN] ASC,
	[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [Person].[Address] ADD  CONSTRAINT [DF_Address_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO
ALTER TABLE [Person].[LanguagesSpoken] ADD  CONSTRAINT [DF_LanguagesSpoken_rowid]  DEFAULT (newid()) FOR [rowid]
GO
ALTER TABLE [Person].[LUAddressType] ADD  CONSTRAINT [DF_AddressType_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO
ALTER TABLE [Person].[LUContactType] ADD  CONSTRAINT [DF_ContactType_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO
ALTER TABLE [Person].[LUState] ADD  CONSTRAINT [DF_State_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO
ALTER TABLE [Person].[Person] ADD  CONSTRAINT [DF_Person_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO
ALTER TABLE [dbo].[GuidelinesByProgram]  WITH CHECK ADD  CONSTRAINT [FK_GuidelinesByProgram_LUStateFederalProgram] FOREIGN KEY([ProgramID])
REFERENCES [dbo].[LUStateFederalProgram] ([StateFederalProgramID])
GO
ALTER TABLE [dbo].[GuidelinesByProgram] CHECK CONSTRAINT [FK_GuidelinesByProgram_LUStateFederalProgram]
GO
ALTER TABLE [dbo].[GuidelinesByProgram]  WITH CHECK ADD  CONSTRAINT [FK_GuidelinesByProgram_ProgramGuidelines] FOREIGN KEY([GuidelinesID])
REFERENCES [dbo].[ProgramGuidelines] ([ProgramGuidelinesID])
GO
ALTER TABLE [dbo].[GuidelinesByProgram] CHECK CONSTRAINT [FK_GuidelinesByProgram_ProgramGuidelines]
GO
ALTER TABLE [Foodshelf].[FoodShelfCertification]  WITH CHECK ADD  CONSTRAINT [FK_FoodShelfCertification_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Foodshelf].[FoodShelfCertification] CHECK CONSTRAINT [FK_FoodShelfCertification_Person]
GO
ALTER TABLE [Foodshelf].[FoodTypeGiven]  WITH CHECK ADD  CONSTRAINT [FK_FoodTypeGiven_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Foodshelf].[FoodTypeGiven] CHECK CONSTRAINT [FK_FoodTypeGiven_Person]
GO
ALTER TABLE [Foodshelf].[HouseholdNotes]  WITH CHECK ADD  CONSTRAINT [FK_HouseholdNotes_Person] FOREIGN KEY([ClientPersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Foodshelf].[HouseholdNotes] CHECK CONSTRAINT [FK_HouseholdNotes_Person]
GO
ALTER TABLE [Foodshelf].[Signature]  WITH CHECK ADD  CONSTRAINT [FK_Signature_FoodShelfCertification] FOREIGN KEY([FoodShelfCertificationID], [PersonID])
REFERENCES [Foodshelf].[FoodShelfCertification] ([FoodShelfCertificationID], [PersonID])
GO
ALTER TABLE [Foodshelf].[Signature] CHECK CONSTRAINT [FK_Signature_FoodShelfCertification]
GO
ALTER TABLE [Person].[Demographics]  WITH CHECK ADD  CONSTRAINT [FK_Deomographics_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[Demographics] CHECK CONSTRAINT [FK_Deomographics_Person]
GO
ALTER TABLE [Person].[FamilyRelationships]  WITH CHECK ADD  CONSTRAINT [FK_FamilyRelationships_Person] FOREIGN KEY([ClientPersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[FamilyRelationships] CHECK CONSTRAINT [FK_FamilyRelationships_Person]
GO
ALTER TABLE [Person].[LanguagesSpoken]  WITH CHECK ADD  CONSTRAINT [FK_LanguagesSpoken_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[LanguagesSpoken] CHECK CONSTRAINT [FK_LanguagesSpoken_Person]
GO
ALTER TABLE [Person].[LUCity]  WITH CHECK ADD  CONSTRAINT [FK_LUCity_LUCounty] FOREIGN KEY([CountyID])
REFERENCES [Person].[LUCounty] ([CountyID])
GO
ALTER TABLE [Person].[LUCity] CHECK CONSTRAINT [FK_LUCity_LUCounty]
GO
ALTER TABLE [Person].[LUCounty]  WITH CHECK ADD  CONSTRAINT [FK_LUCounty_LUState] FOREIGN KEY([StateID])
REFERENCES [Person].[LUState] ([StateID])
GO
ALTER TABLE [Person].[LUCounty] CHECK CONSTRAINT [FK_LUCounty_LUState]
GO
ALTER TABLE [Person].[LUPostalCode]  WITH CHECK ADD  CONSTRAINT [FK_LUPostalCode_LUCity] FOREIGN KEY([CityID])
REFERENCES [Person].[LUCity] ([CityID])
GO
ALTER TABLE [Person].[LUPostalCode] CHECK CONSTRAINT [FK_LUPostalCode_LUCity]
GO
ALTER TABLE [Person].[Notes]  WITH CHECK ADD  CONSTRAINT [FK_HouseholdNotes_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[Notes] CHECK CONSTRAINT [FK_HouseholdNotes_Person]
GO
ALTER TABLE [Person].[PersonAddresses]  WITH CHECK ADD  CONSTRAINT [FK_PersonAddresses_Address] FOREIGN KEY([AddressID])
REFERENCES [Person].[Address] ([AddressID])
GO
ALTER TABLE [Person].[PersonAddresses] CHECK CONSTRAINT [FK_PersonAddresses_Address]
GO
ALTER TABLE [Person].[PersonAddresses]  WITH CHECK ADD  CONSTRAINT [FK_PersonAddresses_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[PersonAddresses] CHECK CONSTRAINT [FK_PersonAddresses_Person]
GO
ALTER TABLE [Person].[Phone]  WITH CHECK ADD  CONSTRAINT [FK_Phone_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[Phone] CHECK CONSTRAINT [FK_Phone_Person]
GO
ALTER TABLE [Person].[Programs]  WITH CHECK ADD  CONSTRAINT [FK_Programs_Person] FOREIGN KEY([PersonID])
REFERENCES [Person].[Person] ([PersonID])
GO
ALTER TABLE [Person].[Programs] CHECK CONSTRAINT [FK_Programs_Person]
GO
ALTER TABLE [Person].[ProgramServicesUsed]  WITH CHECK ADD  CONSTRAINT [FK_ProgramServicesUsed_Programs] FOREIGN KEY([PersonID], [ProgramID])
REFERENCES [Person].[Programs] ([PersonID], [ProgramID])
GO
ALTER TABLE [Person].[ProgramServicesUsed] CHECK CONSTRAINT [FK_ProgramServicesUsed_Programs]
GO
ALTER TABLE [Signature].[Signatures]  WITH CHECK ADD  CONSTRAINT [FK_Signatures_Signature1] FOREIGN KEY([SignatureID], [PersonID])
REFERENCES [Signature].[Signature] ([SignatureID], [PersonID])
GO
ALTER TABLE [Signature].[Signatures] CHECK CONSTRAINT [FK_Signatures_Signature1]
GO
ALTER TABLE [Volunteer].[VolunteerContactInformation]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerContactInformation_Organization] FOREIGN KEY([OrganizationID])
REFERENCES [dbo].[Organization] ([OrganizationID])
GO
ALTER TABLE [Volunteer].[VolunteerContactInformation] CHECK CONSTRAINT [FK_VolunteerContactInformation_Organization]
GO
ALTER TABLE [Volunteer].[VolunteerEmergencyContact]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerEmergencyContact_VolunteerContactInformation] FOREIGN KEY([VolunteerPersonID])
REFERENCES [Volunteer].[VolunteerContactInformation] ([VolunteerPersonID])
GO
ALTER TABLE [Volunteer].[VolunteerEmergencyContact] CHECK CONSTRAINT [FK_VolunteerEmergencyContact_VolunteerContactInformation]
GO
ALTER TABLE [Volunteer].[VolunteerJobs]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerJobs_VolunteerContactInformation] FOREIGN KEY([VolunteerPersonID])
REFERENCES [Volunteer].[VolunteerContactInformation] ([VolunteerPersonID])
GO
ALTER TABLE [Volunteer].[VolunteerJobs] CHECK CONSTRAINT [FK_VolunteerJobs_VolunteerContactInformation]
GO
ALTER TABLE [Volunteer].[VolunteerNotes]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerNotes_VolunteerContactInformation] FOREIGN KEY([VolunteerPersonID])
REFERENCES [Volunteer].[VolunteerContactInformation] ([VolunteerPersonID])
GO
ALTER TABLE [Volunteer].[VolunteerNotes] CHECK CONSTRAINT [FK_VolunteerNotes_VolunteerContactInformation]
GO
ALTER TABLE [Volunteer].[VolunteerScheduleDayTime]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerScheduleDayTime_VolunteerScheduleWeek] FOREIGN KEY([VolunteerScheduleWeekID])
REFERENCES [Volunteer].[VolunteerScheduleWeek] ([VolunteerScheduleWeekID])
GO
ALTER TABLE [Volunteer].[VolunteerScheduleDayTime] CHECK CONSTRAINT [FK_VolunteerScheduleDayTime_VolunteerScheduleWeek]
GO
ALTER TABLE [Volunteer].[VolunteerScheduleMonth]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerScheduleMonth_VolunteerContactInformation] FOREIGN KEY([VolunteerPersonID])
REFERENCES [Volunteer].[VolunteerContactInformation] ([VolunteerPersonID])
GO
ALTER TABLE [Volunteer].[VolunteerScheduleMonth] CHECK CONSTRAINT [FK_VolunteerScheduleMonth_VolunteerContactInformation]
GO
ALTER TABLE [Volunteer].[VolunteerScheduleWeek]  WITH CHECK ADD  CONSTRAINT [FK_VolunteerScheduleWeek_VolunteerScheduleMonth] FOREIGN KEY([VolunteerScheduleMonthID])
REFERENCES [Volunteer].[VolunteerScheduleMonth] ([VolunteerScheduleMonthID])
GO
ALTER TABLE [Volunteer].[VolunteerScheduleWeek] CHECK CONSTRAINT [FK_VolunteerScheduleWeek_VolunteerScheduleMonth]
GO
/****** Object:  StoredProcedure [Maintenance].[CreateRoleScript]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Written By Bradley Morris
--In Query Analyzer be sure to go to
--Query -> Current Connection Options -> Advanced (Tab)
--and set Maximum characters per column
--to a high number, such as 10000, so
--that all the code will be displayed.

Create Procedure [Maintenance].[CreateRoleScript](@RoleName [SYSNAME])
As

--Written By Bradley Morris
--In Query Analyzer be sure to go to
--Query -> Current Connection Options -> Advanced (Tab)
--and set Maximum characters per column
--to a high number, such as 10000, so
--that all the code will be displayed.

DECLARE  @DatabaseRoleName [SYSNAME]
--SET @DatabaseRoleName = '{Database Role Name}'

--SET @DatabaseRoleName = 'role_name_goes_here'
SET @DatabaseRoleName =@RoleName

SET NoCount  ON

DECLARE  @errStatement      [VARCHAR](8000),
         @msgStatement      [VARCHAR](8000),
         @DatabaseRoleID    [SMALLINT],
         @IsApplicationRole [BIT],
         @ObjectID          [INT],
         @ObjectName        [SYSNAME]

SELECT @DatabaseRoleID = [uId],
       @IsApplicationRole = CAST([IsapProle] AS BIT)
FROM   [dbo].[sysUsers]
WHERE  [Name] = @DatabaseRoleName
       AND ([IssqlRole] = 1
             OR [IsapProle] = 1)
       AND [Name] NOT IN ('public',
                          'INFORMATION_SCHEMA',
                          'db_owner',
                          'db_accessadmin',
                          'db_securityadmin',
                          'db_ddladmin',
                          'db_backupoperator',
                          'db_datareader',
                          'db_datawriter',
                          'db_denydatareader',
                          'db_denydatawriter')

IF @DatabaseRoleID IS NULL
  BEGIN
    IF @DatabaseRoleName IN ('public',
                             'INFORMATION_SCHEMA',
                             'db_owner',
                             'db_accessadmin',
                             'db_securityadmin',
                             'db_ddladmin',
                             'db_backupoperator',
                             'db_datareader',
                             'db_datawriter',
                             'db_denydatareader',
                             'db_denydatawriter')
      SET @errStatement = 'Role ' + @DatabaseRoleName + ' is a fixed database role and cannot be scripted.'
    ELSE
      SET @errStatement = 'Role ' + @DatabaseRoleName + ' does not exist in ' + Db_name() + '.' + CHAR(13) + 'Please provide the name of a current role in ' + Db_name() + ' you wish to script.'
    RAISERROR (@errStatement,16,1)
  END
ELSE
  BEGIN
    SET @msgStatement = '--Security creation script for role ' + @DatabaseRoleName + CHAR(13) + '--Created At: ' + CONVERT(VARCHAR,Getdate(),112) + REPLACE(CONVERT(VARCHAR,Getdate(),108),':','') + CHAR(13) + '--Created By: ' + Suser_name() + CHAR(13) + '--Add Role To Database' + CHAR(13)
    IF @IsApplicationRole = 1
      SET @msgStatement = @msgStatement + 'EXEC sp_addapprole' + CHAR(13) + CHAR(9) + '@rolename = ''' + @DatabaseRoleName + '''' + CHAR(13) + CHAR(9) + '@password = ''{Please provide the password here}''' + CHAR(13)
    ELSE
      BEGIN
        SET @msgStatement = @msgStatement + 'EXEC sp_addrole' + CHAR(13) + CHAR(9) + '@rolename ''' + @DatabaseRoleName + '''' + CHAR(13)
        PRINT 'GO'
      END
    SET @msgStatement = @msgStatement + '--Set Object Specific Permissions For Role'
    PRINT @msgStatement
    DECLARE _sySobjects CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR
    SELECT DISTINCT ([sySobjects].[Id]),
                    '[' + User_name([sySobjects].[uId]) + '].[' + [sySobjects].[Name] + ']'
    FROM   [dbo].[sysProtects]
           INNER JOIN [dbo].[sySobjects]
             ON [sysProtects].[Id] = [sySobjects].[Id]
    WHERE  [sysProtects].[uId] = @DatabaseRoleID
    OPEN _sySobjects
    FETCH NEXT FROM _sySobjects
    INTO @ObjectID,
         @ObjectName
    WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @msgStatement = ''
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 193
                          AND [ProtectType] = 205)
          SET @msgStatement = @msgStatement + 'SELECT,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 195
                          AND [ProtectType] = 205)
          SET @msgStatement = @msgStatement + 'INSERT,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 197
                          AND [ProtectType] = 205)
          SET @msgStatement = @msgStatement + 'UPDATE,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 196
                          AND [ProtectType] = 205)
          SET @msgStatement = @msgStatement + 'DELETE,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 224
                          AND [ProtectType] = 205)
          SET @msgStatement = @msgStatement + 'EXECUTE,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 26
                          AND [ProtectType] = 205)
          SET @msgStatement = @msgStatement + 'REFERENCES,'
        IF len(@msgStatement) > 0
          BEGIN
            IF RIGHT(@msgStatement,1) = ','
              SET @msgStatement = LEFT(@msgStatement,Len(@msgStatement) - 1)
            SET @msgStatement = 'GRANT' + CHAR(13) + CHAR(9) + @msgStatement + CHAR(13) + CHAR(9) + 'ON ' + @ObjectName + CHAR(13) + CHAR(9) + 'TO ' + @DatabaseRoleName
            PRINT @msgStatement
          END
        SET @msgStatement = ''
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 193
                          AND [ProtectType] = 206)
          SET @msgStatement = @msgStatement + 'SELECT,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 195
                          AND [ProtectType] = 206)
          SET @msgStatement = @msgStatement + 'INSERT,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 197
                          AND [ProtectType] = 206)
          SET @msgStatement = @msgStatement + 'UPDATE,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 196
                          AND [ProtectType] = 206)
          SET @msgStatement = @msgStatement + 'DELETE,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 224
                          AND [ProtectType] = 206)
          SET @msgStatement = @msgStatement + 'EXECUTE,'
        IF EXISTS (SELECT *
                   FROM   [dbo].[sysProtects]
                   WHERE  [Id] = @ObjectID
                          AND [uId] = @DatabaseRoleID
                          AND [Action] = 26
                          AND [ProtectType] = 206)
          SET @msgStatement = @msgStatement + 'REFERENCES,'
        IF len(@msgStatement) > 0
          BEGIN
            IF RIGHT(@msgStatement,1) = ','
              SET @msgStatement = LEFT(@msgStatement,Len(@msgStatement) - 1)
            SET @msgStatement = 'DENY' + CHAR(13) + CHAR(9) + @msgStatement + CHAR(13) + CHAR(9) + 'ON ' + @ObjectName + CHAR(13) + CHAR(9) + 'TO ' + @DatabaseRoleName
            PRINT @msgStatement
          END
        FETCH NEXT FROM _sySobjects
        INTO @ObjectID,
             @ObjectName
      END
    CLOSE _sySobjects
    DEALLOCATE _sySobjects
    PRINT 'GO'
  END
GO
/****** Object:  StoredProcedure [Maintenance].[pFamilyMemberStartsNewHousehold]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
*
*Author: Gary Savard
*Date: 15 April 2011
*
Description: This SP covers the instances where a family member starts a new household. This is really only removing 
them from their current household since the record type is the same for client and family members. 
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pFamilyMemberStartsNewHousehold](
	@ClientPersonID int, -- The old client that the person moving is associated with.
	@FamilyToClientPersonID int,--The person who is creating a  new household.
	@ModifiedBy name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int,
	@PersonID int,
	@Notes NVarchar(100),
	@ErrNo int
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempPersonID =0;
	SET @ErrNo =0;		

	
	           
BEGIN TRY
	 BEGIN TRANSACTION;
	--We first check to be sure that the @FamilyToClientPersonID is in the db
	--Check to see that the old @ClientToPersonID is in the db
	 --if either fails, then bail!
	--Place a record in the Journal Table with the appropriate information before making the change. 
	--Remove the new client from the FamilyRelationship table
	--Make update to  Family relationships table table for new family status. This will probably be blank since we will 
	--want the family to be created on the new query.
	 

	

	 --We need them BOTH to be in the FamilyRelationship table in the same record, else the system does not know that they are related!
		IF EXISTS(SELECT * from person.FamilyRelationships where PersonID =@FamilyToClientPersonID AND ClientPersonID=@ClientPersonID)
			BEGIN
				--Create a string to pass into notes in journal
				SET @Notes = 'Create new household for Person = ' + @FamilyToClientPersonID + 'Previous Household''s Head = ' + @ClientPersonID + 'old household tie removed from FamilyRelationships table'
				
				 					--Time to remove the person. We need to only remove them from the FamilyRelationships table. They will have to Certify when they come in.
						
					DELETE FROM Person.FamilyRelationships WHERE PersonID = @FamilyToClientPersonID AND ClientPersonID = @ClientPersonID
					
					SELECT @ErrNo=@@ERROR
					
					IF @ErrNo<>0
						BEGIN
							SET @ErrorStatus ='Failed on Delete Family Member PersonID: ' + CONVERT(NVarchar(50),@FamilyToClientPersonID)
							RAISERROR(@ErrorStatus,16,0)
					
						END--IF@ErrNO
						
				--Make Journal Entry. We are ignoring potential errors from journal for the time being. 
				 EXEC pInsertJournalClientFamilyChanges @FamilyToClientPersonID,@ClientPersonID,0,'New Household Created','',@ModifiedBY,@Success OUTPUT,@ErrorStatus OUTPUT
				 
					
			
			END
		ELSE
			BEGIN
				SET @ErrorStatus ='Client/House member not matched FamRel tab : ' + CONVERT(NVarchar(50),@FamilyToClientPersonID) + ' ' + CONVERT(NVarchar(50),@ClientPersonID)
							RAISERROR(@ErrorStatus,16,0)
			
			END
	
	
	/******************************************************************************************************
	 
	 
	
	*******************************************************************************************************/
		COMMIT TRANSACTION;
	
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SET @ErrorStatus=  @ErrorStatus + '-1001';
			  RAISERROR(@ErrorStatus, 15, 1);
		
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [Maintenance].[pGrantViewDefinitionsforUDTs]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [Maintenance].[pGrantViewDefinitionsforUDTs] 
	
AS
BEGIN

DECLARE

@UDTName NVarchar(30),
@SchemaID int,
@SchemaName NVarchar(30),
@Cnt int,
@NumRec int,
@ExecString NVarchar(200)



CREATE TABLE #TempTable (counts INT identity,name Varchar(50),SchemaID int)
INSERT INTO #TempTable  SELECT name,schema_id FROM sys.Types 
WHERE is_user_defined = 1

SELECT @NumRec = MAX(Counts) from #TempTable

SET @Cnt =1

While @Cnt <= @NumRec
	BEGIN
		SELECT @UDTName =name, @SchemaID =SCHEMAID from #TempTable where counts =@Cnt
	
		SELECT @SchemaName =name from sys.schemas where schema_id =@SchemaID
	
	SET @ExecString =	'GRANT VIEW DEFINITION ON TYPE::[' + @SchemaName + '].' + @UDTNAME + ' TO db_CrystalReports'
	
	EXEC (@ExecString)
	
	SET @Cnt = @Cnt +1
	
	END 
Drop Table #TempTable
	
END

GO
/****** Object:  StoredProcedure [Maintenance].[pHideAddressType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 21 July 2011
*Table Name: LUAddressType
Description: Suppresses from LUAddressType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideAddressType](
	@AddressTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempAddressTypeID int
	
	SET @TempAddressTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@AddressTypeID = 0) OR (@AddressTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6015 AddressTypeID cannot be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempAddressTypeID =@AddressTypeID
				  FROM person.LUAddressType
					 WHERE  AddressTypeID= @AddressTypeID
			
								 
				IF ((@TempAddressTypeID=0) OR (@TempAddressTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6018 AddressTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE  Person.LUAddressType
					 SET IsDeleted =1
					 WHERE AddressTypeID = @AddressTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6013 DELETE Fail AddressType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideCity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date:21 July 2011
*Table Name: LUCity
Description: Hides row in LUCity
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideCity](
	@CityID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempCityID int
	
	SET @TempCityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@CityID = 0) OR (@CityID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60055 CityID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempCityID =@CityID
				  FROM person.LUCity
					 WHERE  CityID= @CityID
			
								 
				IF ((@TempCityID=0) OR (@TempCityID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60058 CityID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60050';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

					UPDATE  Person.LUCity SET IsDeleted =1
					 WHERE CityID = @CityID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60053 DELETE Fail City';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideContactType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 21 July 2011
*Table Name: LUContactType
Description: Hides LUContactType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideContactType](
	@ContactTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempContactTypeID int
	
	SET @TempContactTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ContactTypeID = 0) OR (@ContactTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60025 ContactTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempContactTypeID =ContactTypeID
				  FROM person.LUContactType
					 WHERE  ContactTypeID= @ContactTypeID
			
								 
				IF ((@TempContactTypeID=0) OR (@TempContactTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60028 ContactTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60020';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE  Person.LUContactType
					 SET IsDeleted =1
					 WHERE ContactTypeID = @ContactTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60023 DELETE Fail ContactType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideEducationCategory]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





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

*Author: Gary Savard
*Date: 21 July 2011
*Table Name: LUEducationCategory
Description: Hides LUEducationCategory
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideEducationCategory](
	@EducationCategoryID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempEducationCategoryID int

	
	SET @TempEducationCategoryID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@EducationCategoryID = 0) OR (@EducationCategoryID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60065 EducationCategoryID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempEducationCategoryID = EducationCategoryID 
				  FROM person.LUEducationCategory
					 WHERE EducationCategoryID = @TempEducationCategoryID
			
								 
				IF ((@TempEducationCategoryID=0) OR (@TempEducationCategoryID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60078 EducationCategoryID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE   Person.LUEducationCategory
					 SET IsDeleted =1
					 WHERE EducationCategoryID = @EducationCategoryID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60073 DELETE Fail EducationCategory';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideEthnicity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: LUEthnicity
Description: Hides LUEthicity
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideEthnicity](
	@EthnicityID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempEthnicityID int
	
	SET @TempEthnicityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@EthnicityID = 0) OR (@EthnicityID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60085 EthnicityID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempEthnicityID =EthnicityID  
				  FROM person.LUEthnicity
					 WHERE EthnicityID = @TempEthnicityID
			
								 
				IF ((@TempEthnicityID=0) OR (@TempEthnicityID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60088 EthnicityID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE  Person.LUEthnicity
					 SET IsDeleted =1
					 WHERE EthnicityID = @EthnicityID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60083 DELETE Fail Ethnicity';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideFamilyStatusType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 14 March 11
*Table Name: LUFamilyStatusType
Description: Hides LUFamilyStatusType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideFamilyStatusType](
	@FamilyStatusTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempFamilyStatusTypeID int
	
	SET @FamilyStatusTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@FamilyStatusTypeID = 0) OR (@FamilyStatusTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600015 FamilyStatusTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @FamilyStatusTypeID =FamilySTatusTypeID  
				  FROM person.LUFamilyStatusType
					 WHERE FamilyStatusTypeID = @FamilyStatusTypeID
			
								 
				IF ((@TempFamilyStatusTypeID=0) OR (@TempFamilyStatusTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600018 FamilySTatusTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE  Person.LUFamilyStatusType
					 SET IsDeleted =1
					 WHERE FamilyStatusTypeID = @FamilyStatusTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail LuFamilyStatusType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END














GO
/****** Object:  StoredProcedure [Maintenance].[pHideHouseholdTransferOptions]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: HouseholdTransferOptions
Description: Hides from HouseholdTransferOptions. 
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideHouseholdTransferOptions](
	@ActionToTakeID  int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempActionToTakeID int
	
	SET @TempActionToTakeID  =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ActionToTakeID = 0) OR (@ActionToTakeID  IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6015 ActionToTakeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempActionToTakeID =@ActionToTakeID 
				  FROM dbo.LUHouseholdTransferOptions
					 WHERE  HouseholdTransferActionID= @ActionToTakeID
			
								 
				IF ((@TempActionToTakeID=0) OR (@TempActionToTakeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6018 ActionToTakeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE  dbo.LUHouseholdTransferOptions
					 SET IsDeleted =1	
					 WHERE HouseholdTransferActionID = @TempActionToTakeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6013 DELETE Fail LUHouseholdTransferOptions';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END













GO
/****** Object:  StoredProcedure [Maintenance].[pHideHousingStatus]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 21 July
*Table Name: LUHousingStatus
Description: Hides LUHousingStatus
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideHousingStatus](
	@HousingStatusID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempHousingStatusID int
	
	SET @TempHousingStatusID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@HousingStatusID = 0) OR (@HousingStatusID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60085 HousingStatusID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempHousingStatusID =HousingStatusID
				  FROM person.LUHousingStatus
					 WHERE  HousingStatusID= @HousingStatusID
			
								 
				IF ((@TempHousingStatusID=0) OR (@TempHousingStatusID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60088 HousingStatusID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60080';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE  Person.LUHousingStatus
					 SET IsDeleted =1
					 WHERE HousingStatusID = @HousingStatusID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60083 DELETE Fail HousingStatus';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideIncomeSource]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: LUIncomeSource
Description: Hides LUIncomeSource
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideIncomeSource](
	@IncomeSourceID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempIncomeSourceID int
	
	SET @TempIncomeSourceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@IncomeSourceID = 0) OR (@IncomeSourceID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60095 IncomeSourceID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempIncomeSourceID = IncomeSourceID 
				  FROM person.LUIncomeSource
					 WHERE IncomeSourceID = @IncomeSourceID
			
								 
				IF ((@TempIncomeSourceID=0) OR (@TempIncomeSourceID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60098 IncomeSourceID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE   Person.LUIncomeSource
					 SET IsDeleted =1
					 WHERE IncomeSourceID = @IncomeSourceID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60093 DELETE Fail IncomeSource';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideInsuranceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: LUInsuranceType
Description: Hides LUInsuranceType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideInsuranceType](
	@InsuranceTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempInsuranceTypeID int
	
	SET @InsuranceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@InsuranceTypeID = 0) OR (@InsuranceTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600015 InsuranceTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @InsuranceTypeID =InsuranceTypeID  
				  FROM person.LUInsuranceType
					 WHERE InsuranceTypeID = @InsuranceTypeID
			
								 
				IF ((@TempInsuranceTypeID=0) OR (@TempInsuranceTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600018 InsuranceTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE Person.LUInsuranceType
					 SET IsDeleted =1
					 WHERE InsuranceTypeID = @InsuranceTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail LuInsuranceType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END













GO
/****** Object:  StoredProcedure [Maintenance].[pHideLanguage]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date:21 July 11
*Table Name: LULanguage
Description: Deletes from LULanguage
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideLanguage](
	@LanguageID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempLanguageID int
	
	SET @TempLanguageID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@LanguageID = 0) OR (@LanguageID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60065 LanguageID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempLanguageID = LanguageID 
				  FROM person.LULanguage
					 WHERE LanguageID = @LanguageID
			
								 
				IF ((@TempLanguageID=0) OR (@TempLanguageID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60068 LanguageID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE Person.LULanguage
					 SET IsDeleted =1
					 WHERE LanguageID = @LanguageID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60063 DELETE Fail Language';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideLUFamilyRelationship]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: LUFamilyRelationship
Description: Hide LUFamilyRelationship
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideLUFamilyRelationship](
	@FamilyRelationshipID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempFamilyRelationshipID int
	
	SET @TempFamilyRelationshipID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@FamilyRelationshipID = 0) OR (@FamilyRelationshipID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60045 FamilyRelationshipID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempFamilyRelationshipID =FamilyRelationshipID
				  FROM person.LUFamilyRelationship
					 WHERE  FamilyRelationshipID= @FamilyRelationshipID
			
								 
				IF ((@TempFamilyRelationshipID=0) OR (@TempFamilyRelationshipID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60048 FamilyRelationshipID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60040';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE  Person.LUFamilyRelationship
					 SET IsDeleted =1
					 WHERE FamilyRelationshipID = @FamilyRelationshipID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60043 DELETE Fail FamilyRelationship';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHidePersonType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUPersonType
Description: Hides LUPersonType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHidePersonType](
	@PersonTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPersonTypeID int
	
	SET @TempPersonTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@PersonTypeID = 0) OR (@PersonTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600015 PersonTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempPersonTypeID =PersonTypeID  
				  FROM person.LUPersonType
					 WHERE PersonTypeID = @PersonTypeID
			
								 
				IF ((@TempPersonTypeID=0) OR (@TempPersonTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600018 PersonTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE  Person.LUPersonType
					 SET IsDeleted =1
					 WHERE PersonTypeID = @PersonTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail PersonType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHidePhoneType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUPhoneType
Description: HideLUPhoneType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHidePhoneType](
	@PhoneTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPhoneTypeID int
	
	SET @TempPhoneTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@PhoneTypeID = 0) OR (@PhoneTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600085 PhoneTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempPhoneTypeID =PhoneTypeID  
				  FROM person.LUPhoneType
					 WHERE PhoneTypeID = @PhoneTypeID
			
								 
				IF ((@TempPhoneTypeID=0) OR (@TempPhoneTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600088 PhoneTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600080';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE  Person.LUPhoneType
					 SET IsDeleted =1
					 WHERE PhoneTypeID = @PhoneTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600083 DELETE Fail PhoneType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END













GO
/****** Object:  StoredProcedure [Maintenance].[pHidePostalCode]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: LUPostalCode
Description: Hides LUPostalCode
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHidePostalCode](
	@PostalCodeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPostalCodeID int
	
	SET @TempPostalCodeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@PostalCodeID = 0) OR (@PostalCodeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6075 PostalCodeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempPostalCodeID =PostalCodeID
				  FROM person.LUPostalCode
					 WHERE  PostalCodeID= @PostalCodeID
			
								 
				IF ((@TempPostalCodeID=0) OR (@TempPostalCodeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6078 PostalCodeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6070';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE Person.LUPostalCode
					 SET IsDeleted =1
					 WHERE PostalCodeID = @PostalCodeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6073 DELETE Fail PostalCode';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideProgramServiceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUProgramServiceType
Description: Hides LUProgramServiceType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideProgramServiceType](
	@ProgramServiceTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempProgramServiceTypeID int
	
	SET @TempProgramServiceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ProgramServiceTypeID = 0) OR (@ProgramServiceTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6055 ProgramServiceTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempProgramServiceTypeID =ProgramServiceTypeID
				  FROM person.LUProgramServiceType
					 WHERE  ProgramServiceTypeID= @ProgramServiceTypeID
			
								 
				IF ((@TempProgramServiceTypeID=0) OR (@TempProgramServiceTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6058 ProgramServiceTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6050';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE Person.LUProgramServiceType
					 SET IsDeleted =1
					 WHERE ProgramServiceTypeID = @ProgramServiceTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6053 DELETE Fail ProgramServiceType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideProgramType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 21 July 11
*Table Name: LUProgramType
Description: Hides LUProgramType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideProgramType](
	@ProgramTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempProgramTypeID int
	
	SET @TempProgramTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ProgramTypeID = 0) OR (@ProgramTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6045 ProgramTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempProgramTypeID =ProgramTypeID
				  FROM person.LUProgramType
					 WHERE  ProgramTypeID= @ProgramTypeID
			
								 
				IF ((@TempProgramTypeID=0) OR (@TempProgramTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6048 ProgramTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6040';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE  Person.LUProgramType
					 SET IsDeleted =1
					 WHERE ProgramTypeID = @ProgramTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6043 DELETE Fail PostalCode';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideRace]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LURace
Description: Hides LURace
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideRace](
	@RaceID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempRaceID int
	
	SET @TempRaceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@RaceID = 0) OR (@RaceID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6025 RaceID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempRaceID =RaceID
				  FROM person.LURace
					 WHERE  RaceID= @RaceID
			
								 
				IF ((@TempRaceID=0) OR (@TempRaceID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6028 RaceID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6020';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				UPDATE Person.LURace
					 SET IsDeleted =1
					 WHERE RaceID = @RaceID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6023 DELETE Fail Race';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pHideState]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUState
Description: Hides LUState
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pHideState](
	@StateID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempStateID int
	
	SET @TempStateID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@StateID = 0) OR (@StateID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6035 StateID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempStateID =StateID
				  FROM person.LUState
					 WHERE  StateID= @StateID
			
								 
				IF ((@TempStateID=0) OR (@TempStateID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6038 StateID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6030';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 UPDATE Person.LUState
					 SET IsDeleted =1
					 WHERE StateID = @StateID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6033 DELETE Fail State';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [Maintenance].[pMakeFamilyMemberClientinSameHousehold]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO









/*************************************************************************************************
*
*Author: Gary Savard
*Date: 15 April 2011
*
Description: This SP covers the instances where a family member replaces the current client and becomes the client. 
*We handle the client by either deleting (supressing) from the system, moving the client to another household, creating
*another household or by 'demoting' the client to family member. 
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pMakeFamilyMemberClientinSameHousehold](
	@ClientPersonID int,
	@PromoteToClientPersonID int,
	@ActionToTake nVarchar(10),
	@NewPersonID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int,
	@PersonID int;
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempPersonID =0;		

	
	           
BEGIN TRY
	 BEGIN TRANSACTION;
	--Make sure that the @ActionToTake value is valid. If not, bail!
	 
	-- Check the @PromoteToClientPersonID to ensure that the person to be promoted is associated with the current client.
		--If Not Valid, Bail
		--Else
			--all of the household member IDs from the FamilyRelationship table so that we can update the ClientPersonID to that of the new client.
			--Change the Family status of the new client to reflect that they are no longer child, spouse, etc, of the client
	
	
	--If this works, then we will deal with the old client.
	
	--"DEMOTE" If the old client is to become a member of the same household
		--We add them to the FamilyRelationship table and give them a FamilyMember entry
		 
	--If they are part of a new household, then we update any records in the familyRelationship table that has their ID and 
	--Remove any from the FamilyRelationship status as appropriate
	
	--"DELETE" We remove the client by setting the IsDeleted bit in the person table. We keep them in the system,but
	--they are no longer visible from a query.		
	
	--"NEWHOUSEHOLD" -- We create a new household and return the new household ID. May not even need to do that because we are 
	--really just removing their association with the current client. When the move is finished. The person inputting data will have
	--to query on the new record and create the appropriate household members.
	
	
	/******************************************************************************************************
	
	 
	
	*******************************************************************************************************/
		COMMIT TRANSACTION;
	
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SET @ErrorStatus=  @ErrorStatus + '-1001';
			  RAISERROR(@ErrorStatus, 15, 1);
		
			  
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [Maintenance].[pMoveFamilyMemberToAnotherHousehold]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
*
*Author: Gary Savard
*Date: 15 April 2011
*
Description: This SP covers the instances where a family member moves to a new household. It assumes that if the 
person is the head of the old household, that another person has been promoted to head of that household already
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pMoveFamilyMemberToAnotherHousehold](
	@OldHouseholdClientPersonID int, -- The old client that the person moving is associated with.
	@NewHouseholdClientPersonID int,--Person moving to new household
	@ToNewHouseholdPersonID int,--The person who going to new household
	@NewFamilyStatusType NVarchar(50) = NULL,--This may or may not be used.
	@NewFamilyRelationshipID int =0, --May or may not be used.
	@NewFamilyRelationshipDescription NVarchar(50)=NULL, --This may or may not be used
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@ErrNo int
	
	
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @ErrNo =0;	

	
	           
BEGIN TRY
	 BEGIN TRANSACTION;
	--Place a record in the Journal Table with the appropriate information before making the change. 
	--Update the Relationship table with the new household's client ID and the new relationship
	--Make update to demographics table for new family status. 
	
				 EXEC dbo.pInsertJournalClientFamilyChanges @ToNewHouseholdPersonID,
															@OldHouseholdClientPersonID,
															@NewHouseholdClientPersonId,
															'Moved to new household',
															@NewFamilyRelationshipDescription,
															@ModifiedBy
															
					
						--Move to new household
						INSERT  Person.FamilyRelationships(PersonID,ClientPersonID,RelationshipID,RelationDescription,ModifiedDate,ModifiedBy)
							VALUES
								(@ToNewHouseholdPersonID,@NewHouseholdClientPersonID,@NewFamilyRelationshipID,@NewFamilyRelationshipDescription,SYSDATETIME(),@ModifiedBy)
						--Remove from old Household
						SELECT @ErrNo =@@ERROR 
				
							IF @ErrNo<>0
								BEGIN
									SET @ErrorStatus ='Failed Insert Move to new household'
									RAISERROR(@ErrorStatus,16,0)
							
								END
						
						DELETE FROM person.FamilyRelationships 
							WHERE PersonID = @ToNewHouseholdPersonID AND ClientPersonID=@OldHouseholdClientPersonID
								
							IF @ErrNo<>0
								BEGIN
									SET @ErrorStatus ='Failed Delete Move to new household'
									RAISERROR(@ErrorStatus,16,0)
								END
						
	/******************************************************************************************************
	
	 
	
	*******************************************************************************************************/
		COMMIT TRANSACTION;
	
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @ErrNo);
					END
			  SET @Success =0;
			  SET @ErrorStatus=  @ErrorStatus + '-1001';
			  RAISERROR(@ErrorStatus, 15, 1);
		
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [Maintenance].[pRestoreClientRecord]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*
*Author: Gary Savard
*Date: 15 April 2011
*
Description: This SP covers the instances where a deleted person needs to be restored to the database. We just flip the IsDeleted bit.
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pRestoreClientRecord](
	@tRestorePersonID BatchProcessPersonID READONLY,--The person/Household,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@ErrNo INT,
	@LogMsg NVarchar(50),
	@journalSuccess BIT,
	@JournalErrorStatus NVarchar(50),
	@ErrorCount int,
	@Notes NVarchar(50)
	
	
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @ErrNo =0;	
	SET @LogMsg ='Restored client record. ';
	SET @ErrorCount =0;
		
	           
BEGIN TRY
	DECLARE
	@RowCount int,
	@NumberRecs int,
	@tmpPersonID int,
	@tmpClientPersonID int
					
							
	SET @RowCount =1
					
								
					
	SELECT @NumberRecs = COUNT(*) FROM @tRestorePersonID --How many records?
						
						
		WHILE @RowCount <=@NumberRecs
			BEGIN
				BEGIN TRANSACTION;--TX for each individual record
				
				SET @Notes =''
				
				SELECT @tmpPersonID =PersonID 
					FROM @tRestorePersonID
					WHERE RowID =@Rowcount
			
			UPDATE Person.Person
				SET IsDeleted =0
				WHERE PersonID =@TmpPersonID
				
				SELECT @ErrNo =@@ERROR 
				
				 SET @RowCount = @RowCount + 1
				 
			IF @ErrNo<>0 OR @@ROWCOUNT =0 
				BEGIN
					SET @ErrorCount = @ErrorCount +1
					SET @ErrorStatus ='Fail RestoreID: ' + CONVERT(NVarchar(50),@TmpPersonID)+','
					SET @Notes ='Failed restore PersonID' + CONVERT(NVarchar(50),@TmpPersonID)
					 
					ROLLBACK TRANSACTION --Rollback only the one that failed!
				END--IF@ErrNO	 
			
			IF @@TRANCOUNT >0
				BEGIN
					COMMIT TRANSACTION
					SET @Notes ='Restored PersonID: '+ CONVERT(NVarchar(50),@TmpPersonID)
				END
				
			
			--Place a record in the Journal Table with the appropriate information before making the change. 	
			 EXEC dbo.pInsertJournalClientFamilyChanges @TmpPersonID,
											0,--@HeadofHouseholdPersonID not needed
											0,--@NewHeadOfHouseholdPersonID
											@LogMsg,
											@Notes,
											@ModifiedBy,
											@JournalSuccess,--we don't care about the return values of this and error status for time being
											@JournalErrorStatus	
			END --End While
			
	
		 IF @ErrorCount >0--This goes to the error trap for recording those that failed, but we do not rollback in the error trap.
			BEGIN
				RAISERROR(@ErrorStatus,16,0)
			END
			
			
					
				
						
	/******************************************************************************************************
	
	 
	
	*******************************************************************************************************/
		
	
		END TRY

		BEGIN CATCH
			--We do not rollback here
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @ErrNo);
					END
			  SET @Success =0;
			  SET @ErrorStatus=  @ErrorStatus + '-1001';
			  RAISERROR(@ErrorStatus, 15, 1);
		
			  
		END CATCH
		
















GO
/****** Object:  StoredProcedure [Maintenance].[pRetrieveClientRecords]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 11 Jun 11

Description: Returns the names DOB  of queried records
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pRetrieveClientRecords](
	@IsDeleted bit,
	@IsSoundsLike bit,
	@FirstName Name,--if complete query for all deleted, then we don't need names or dob
	@LastName Name,
	@DOB DateTime,
	@IsAllDeletedRecords bit,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
	DECLARE
	@ErrNO int
	
	SET @ErrNO =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
		
			IF @IsAllDeletedRecords = 1 AND @IsDeleted =1 
				BEGIN
					--Cannot retrieve one record AND all records!
					SET @ErrorStatus ='Error ISAllDeltetedRecords & IsDeleted mutually exclusive, both cannot be True: ' 
							RAISERROR(@ErrorStatus,16,0)
				END
			--return everyone who is delteted
			IF @IsAllDeletedRecords =1 
				BEGIN
					SELECT A.FirstName,A.LastName,A.DateOfBirth, 
						   B.AddressLine1, b.City 
				    FROM Person.[Person] AS A, 
						 Person.Address AS B  
				    WHERE (A.PersonID = B.PersonID) AND A.IsDeleted =1
				END
			--Just one deleted	
			IF 	@IsDeleted =1
				BEGIN
				  SELECT A.FirstName, A.LastName, A.DateofBirth,
						 B.AddressLine1, b.City 
				  FROM person.[Person] AS A,
					    Person.Address as B
				  WHERE (A.PersonID = B.PersonID) AND FirstName = @FirstName AND LastName = @LastName AND DateOfBirth = @DOB AND IsDeleted =1
				END
			--Use soundex on last name to return deleted records like those	
			IF @IsDeleted =1 AND @IsSoundsLike =1
				BEGIN
					SELECT A.FirstName,A.LastName,A.DateOfBirth, 
						   B.AddressLine1, b.City 
				    FROM Person.[Person] AS A, 
						 Person.Address AS B  
				    WHERE (A.personid = B.personid) AND soundex(A.Lastname) =SOUNDEX(@LastName) AND A.IsDeleted =1
					
				END
					
			--Completely different query for non deleted record with soundex using both first and last name because IsDeleted =0 and we could have
			--a ton of Smiths!
			IF @IsDeleted =0 and @IsSoundsLike =1
				BEGIN
					BEGIN
					SELECT A.FirstName,A.LastName,A.DateOfBirth, 
						   B.AddressLine1, b.City 
				    FROM Person.[Person] AS A, 
						 Person.Address AS B  
				    WHERE (A.personid = B.personid) AND SOUNDEX(A.Lastname) =SOUNDEX(@LastName) AND SOUNDEX(a.Firstname) = SOUNDEX (@FirstName) AND A.IsDeleted =0
					
				END
				END		
				
				SELECT @ErrNO = @@ERROR
				
				IF @ErrNo<>0
						BEGIN
							SET @ErrorStatus ='Error on query: ' 
							RAISERROR(@ErrorStatus,16,0)
					
						END--IF@ErrNO
				
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @Errno because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @ErrNO <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @ErrNO);
					END
			  SET @Success =0;
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END














GO
/****** Object:  StoredProcedure [Maintenance].[pRetrieveLookupTables]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



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

*Author: Gary Savard
*Date: 11 Jun 11

Description: Returns the names of all look up tables in CV Connect
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [Maintenance].[pRetrieveLookupTables](
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
	DECLARE
	@ErrNO int
	
	SET @ErrNO =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			
				SELECT * FROM sys.tables WHERE tables.name LIKE 'LU'+'%'
				SELECT @ErrNO =@@ERROR
				
				IF @ErrNo<>0
						BEGIN
							SET @ErrorStatus ='Failed on LU table return: ' 
							RAISERROR(@ErrorStatus,16,0)
					
						END--IF@ErrNO
				
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60063 DELETE Fail Language';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END













GO
/****** Object:  StoredProcedure [dbo].[pDeleteAddress]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Address
Description: Delete data from Address table.This table has the possibility of duplicate rows because
	persons can have more than one address. Make sure that delete haplpens based on AddressID PersonId as extra
	precaution
Revisions:
**************************************************************************************************/

create PROCEDURE [dbo].[pDeleteAddress](
	@AddressID int,
	@PersonID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempAddressID int,
	@TempPersonID int
	
	
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempAddressID =0;
	SET @TempAddressID = 0;
		



		BEGIN TRY
		  BEGIN TRANSACTION;
			
		/****************************************************************************/	
		  
		SELECT @TempAddressID = @AddressID
			FROM Person.Address
				WHERE
					AddressID = @AddressID AND PersonID = @PersonID
		
		IF @TempAddressID = 0 OR @TempAddressID IS NULL
			BEGIN
				SELECT @ErrorStatus='-7015 PersonID/AddressID combo doesnt exist in Address';
				SET @Success =0;
				RAISERROR(@ErrorStatus,16,1);
	
			END			
					
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-7000';
				SET @Success = 0;
				RAISERROR (@ErrorStatus,16,1);
			END
			
			  DELETE FROM Person.Address WHERE AddressID = @AddressID and PersonID = @PersonID;
				
				
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			 --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			 
			 SELECT @ErrorStatus =@ErrorStatus + ' -7001' +' Delete Failed';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END










GO
/****** Object:  StoredProcedure [dbo].[pDeleteAddressType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUAddressType
Description: Deletes from LUAddressType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteAddressType](
	@AddressTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempAddressTypeID int
	
	SET @TempAddressTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@AddressTypeID = 0) OR (@AddressTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6015 AddressTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempAddressTypeID =@AddressTypeID
				  FROM person.LUAddressType
					 WHERE  AddressTypeID= @AddressTypeID
			
								 
				IF ((@TempAddressTypeID=0) OR (@TempAddressTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6018 AddressTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUAddressType
					 WHERE AddressTypeID = @AddressTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6013 DELETE Fail AddressType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteCity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUCity
Description: Deletes from LUCity
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteCity](
	@CityID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempCityID int
	
	SET @TempCityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@CityID = 0) OR (@CityID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60055 CityID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempCityID =@CityID
				  FROM person.LUCity
					 WHERE  CityID= @CityID
			
								 
				IF ((@TempCityID=0) OR (@TempCityID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60058 CityID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60050';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUCity
					 WHERE CityID = @CityID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60053 DELETE Fail City';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteClient]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[pDeleteClient](
	@PersonID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
		@TempPersonID int	
		SET @TempPersonID =0;	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			IF (@PersonID = 0) or (@PersonID) = NULL --Must have a person id to know the person
				BEGIN
					SELECT @ErrorStatus =  '-60055 PersonID cannot be 0 or null';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
	
/****************************************************************************/
			--Check to see if the person exists
			SELECT @TempPersonID = PersonID
				FROM person.person
					WHERE PersonID = @PersonID
					
	     		If (@TempPersonID = NULL) OR (@TempPersonID= 0) 
					BEGIN
						SET @ErrorStatus = ' -60052 PersonID Doesnt Exist in Person table.'; 
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
		
					END	

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

			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60050';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
			 --StateID is not updated because that should not change!
			  UPDATE Person.Person
				SET IsDeleted = 1
				WHERE
					PersonID = @PersonID;
					
			  	set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60051 Delete Failed on Person ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END
GO
/****** Object:  StoredProcedure [dbo].[pDeleteContactType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUContactType
Description: Deletes from LUContactType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteContactType](
	@ContactTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempContactTypeID int
	
	SET @TempContactTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ContactTypeID = 0) OR (@ContactTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60025 ContactTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempContactTypeID =ContactTypeID
				  FROM person.LUContactType
					 WHERE  ContactTypeID= @ContactTypeID
			
								 
				IF ((@TempContactTypeID=0) OR (@TempContactTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60028 ContactTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60020';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUContactType
					 WHERE ContactTypeID = @ContactTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60023 DELETE Fail ContactType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteDemographics]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Demographics
Description: Deletes from Demographics
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteDemographics](
	@DemographicsID int,
	@PersonID int,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempDemographicsID int,
	@TempPersonID int
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempDemographicsID =0;		

	
		
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@DemographicsID = 0) OR (@DemographicsID IS NULL)) OR  ((@PersonID = 0) OR (@PersonID IS NULL))
				  BEGIN
					SELECT @ErrorStatus = '2005 DemographicsID/PersonID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				--Check to see that the IDs match.. paranoid? NO! Have had worse things happen....Data integrity can fail!
				--Could use count but that has some optimization and indexing problems....
				SELECT @TempPersonID = PersonID, @TempDemographicsID = DemographicsID 
				  FROM person.Demographics
					 WHERE PersonID = @PersonID AND DemographicsID = @DemographicsID
			
								 
				IF ((@TempDemographicsID=0) OR (@TempDemographicsID IS  NULL))OR ((@TempPersonID =0) OR (@TempPersonID IS NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -2008 DemographicsID/PersonID combo does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.Demographics
					 WHERE DemographicsID = @DemographicsID AND PersonID = @PersonID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-2001 DELETE Fail Demographics';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteEducationCategory]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUEducationCategory
Description: Deletes from LUEducationCategory
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteEducationCategory](
	@EducationCategoryID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempEducationCategoryID int

	
	SET @TempEducationCategoryID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@EducationCategoryID = 0) OR (@EducationCategoryID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60065 EducationCategoryID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempEducationCategoryID = EducationCategoryID 
				  FROM person.LUEducationCategory
					 WHERE EducationCategoryID = @TempEducationCategoryID
			
								 
				IF ((@TempEducationCategoryID=0) OR (@TempEducationCategoryID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60078 EducationCategoryID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUEducationCategory
					 WHERE EducationCategoryID = @EducationCategoryID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60073 DELETE Fail EducationCategory';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteEthnicity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUEthnicity
Description: Deletes from LUEthicity
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteEthnicity](
	@EthnicityID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempEthnicityID int
	
	SET @TempEthnicityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@EthnicityID = 0) OR (@EthnicityID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60085 EthnicityID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempEthnicityID =EthnicityID  
				  FROM person.LUEthnicity
					 WHERE EthnicityID = @TempEthnicityID
			
								 
				IF ((@TempEthnicityID=0) OR (@TempEthnicityID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60088 EthnicityID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUEthnicity
					 WHERE EthnicityID = @EthnicityID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60083 DELETE Fail Ethnicity';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteFamilyMember]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




/*************************************************************************************************
*
*Author: Gary Savard
*Date: 15 April 2011
*
Description: This SP covers the instances where a family member is deleted from a household. It assumes that if the 
person is the head of the old household, that another person has been promoted to head of that household already. It will also delete 
an entire household, if requested.

REV: 25 July 11. Commented out delete entire household per Carol Paul's request

THIS SP IS NOT BEING USED !!! MAY RETURN IN THE FUTURE!
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteFamilyMember](
	@DeletePersonID int,--The person/Household,
	@HeadofHouseholdPersonID int, --Might be the same as @DeletePersonID if it is the head of household!
	--@NewHeadOfHouseholdPersonID int, --Only filled if the person to be deleted is currently the head of household
	--@IsHouseholdDelete bit,--This set to 1 will delete the entire household
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

--	DECLARE
--	@ErrNo INT,
--	@LogMsg NVarchar(50),
--	@journalSuccess BIT,
--	@JournalErrorStatus NVarchar(50)
	
	
--	SET @Success = 0;
--	SET @ErrorStatus ='';
--	SET @ErrNo =0;	
--	SET @LogMsg ='Deleted from household. IsHouseholdDelete: '+ CONVERT(NVarchar(50),@ISHouseholdDelete)

	
	           
--BEGIN TRY
	-- BEGIN TRANSACTION;
	----Place a record in the Journal Table with the appropriate information before making the change. 
	----Update the Relationship table with the new household's client ID and the new relationship
	----Make update to demographics table for new family status. 
	
	--			 EXEC dbo.pInsertJournalClientFamilyChanges @DeletePersonID,
	--														@HeadofHouseholdPersonID,
	--														@NewHeadOfHouseholdPersonID,
	--														@LogMsg,
	--														'',--Notes Field blank for now
	--														@ModifiedBy,
	--														@JournalSuccess,--we don't care about the return values of this and error status for time being
	--														@JournalErrorStatus
															
					
						
	
		--IF @IsHouseholdDelete =1
		----cursors are evil so we will use a temp table. This assum that the family as a whole is to be deleted.
		--	BEGIN
		--		--We need to retrieve the entire family from the FamilyRelationships table. Using temp table because
		--		--cursors are not very efficient. Do this to isolate this family's records from the main tables to help avoid
		--		--problems with batch updates in main system
							
		--		 DECLARE
		--			@RowCount int,
		--			@NumberRecs int,
		--			@tmpPersonID int,
		--			@tmpClientPersonID int
					
		--			SET @tmpClientPersonID = @HeadOfHouseholdPersonID
					
					
		--			SET @RowCount =1
					
		--		 CREATE TABLE #tempfamily
		--			(RowID int identity(1,1), PersID int)
					
		--			INSERT #tempfamily
					
		--			SELECT PersonID
		--				FROM Person.FamilyRelationships 
		--				WHERE ClientPersonID=@HeadOfHouseholdPersonID
						
		--				SET @NumberRecs = @@ROWCOUNT --How many did we insert into #tempFamily
						
		--				WHILE @RowCount <=@NumberRecs
		--					BEGIN
		--						SELECT @tmpPersonID =PersID 
		--							FROM #tempfamily
		--							WHERE RowID =@Rowcount
							
		--					UPDATE Person.Person
		--						SET IsDeleted =1
		--						WHERE PersonID =@TmpPersonID
								
		--						SELECT @ErrNo =@@ERROR 
								
		--						 SET @RowCount = @RowCount + 1
								
		--					END --End While
					
					--IF @ErrNo<>0
					--	BEGIN
					--		SET @ErrorStatus ='Failed on Delete Family Member PersonID: ' + CONVERT(NVarchar(50),@TmpPersonID)
					--		RAISERROR(@ErrorStatus,16,0)
					
					--	END--IF@ErrNO
							
					
						
					--	--Finally, delete the client
					--	UPDATE person.Person
					--		SET IsDeleted =1
					--		WHERE PersonID =@HeadOfHouseholdPersonID
					--	SELECT @ErrNo =@@ERROR 
					
					--IF @ErrNo<>0
					--	BEGIN
					--		SET @ErrorStatus ='Failed on Delete PersonID: ' + CONVERT(NVarchar(50),@HeadOfHouseholdPersonID)
					--		RAISERROR(@ErrorStatus,16,0)
					
					--	END--@Errno
															
					
				--DROP TABLE #tempfamily
								
			--END
			
			----ELSE IF	 @IsHouseholdDelete =0
			--	BEGIN
			--		--Delete the client
			--		UPDATE Person.Person 
			--			SET IsDeleted =1
			--			WHERE PersonID =@HeadOfHouseholdPersonID
						
			--	SELECT @ErrNo =@@ERROR 
					
			--		IF @ErrNo<>0
			--			BEGIN
			--				SET @ErrorStatus ='Failed on Client Delete'
			--				RAISERROR(@ErrorStatus,16,0)
					
			--			END--@errNO=...
				--END--Else IF
					
				
						
	/******************************************************************************************************
	
	 
	
	--*******************************************************************************************************/
	--	COMMIT TRANSACTION;
	
	--	END TRY

	--	BEGIN CATCH
	--		  ROLLBACK TRANSACTION;
	--		  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
	--			--We only care if the error was not raised by SSE
	--			IF @@ERROR <> 50000
	--				BEGIN
	--					SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @ErrNo);
	--				END
	--		  SET @Success =0;
	--		  SET @ErrorStatus=  @ErrorStatus + '-1001';
	--		  RAISERROR(@ErrorStatus, 15, 1);
		
			  
	--	END CATCH
		















GO
/****** Object:  StoredProcedure [dbo].[pDeleteFamilyStatusType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



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

*Author: Gary Savard
*Date: 14 March 11
*Table Name: LUFamilyStatusType
Description: Deletes from LUFamilyStatusType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteFamilyStatusType](
	@FamilyStatusTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempFamilyStatusTypeID int
	
	SET @FamilyStatusTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@FamilyStatusTypeID = 0) OR (@FamilyStatusTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600015 FamilyStatusTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @FamilyStatusTypeID =FamilySTatusTypeID  
				  FROM person.LUFamilyStatusType
					 WHERE FamilyStatusTypeID = @FamilyStatusTypeID
			
								 
				IF ((@TempFamilyStatusTypeID=0) OR (@TempFamilyStatusTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600018 FamilySTatusTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUFamilyStatusType
					 WHERE FamilyStatusTypeID = @FamilyStatusTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail LuFamilyStatusType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END













GO
/****** Object:  StoredProcedure [dbo].[pDeleteFoodTypeGiven]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: FoodTypeGiven
Description: Deletes from FoodTypeGiven. A person may have 1 to may records here. Deletes only one based
on input ID.
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteFoodTypeGiven](
	@PersonID int,
	@FoodTypeGivenID int, --This is the key. 
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempFoodTypeGivenID int
	
	SET @TempFoodTypeGivenID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@FoodTypeGivenID = 0) OR (@FoodTypeGivenID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600005 FoodTypeGiven cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				  
				  IF ((@PersonID = 0) OR (@PersonID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6000006 PersonID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				--This just avoids deleting a FoodTypeGivenID if it is associated with a different PersonID
				SELECT @TempFoodTypeGivenID =  FoodTypeGivenID
				  FROM Foodshelf.FoodTypeGiven
					 WHERE  PersonID= @PersonID AND FoodTypeGivenID = @FoodTypeGivenID
			
								 
				IF ((@TempFoodTypeGivenID=0) OR (@TempFoodTypeGivenID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600008 FoodTypeGivenID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM Foodshelf.FoodTypeGiven
					 WHERE FoodTypeGivenID = @FoodTypeGivenID AND PersonID = @PersonID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail FoodTypeGiven';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteHouseholdTransferOptions]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 22 April 11
*Table Name: HouseholdTransferOptions
Description: Deletes from HouseholdTransferOptions. Since the fields are free format in this table,
we only take in the ID for deletion
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteHouseholdTransferOptions](
	@ActionToTakeID  int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempActionToTakeID int
	
	SET @TempActionToTakeID  =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ActionToTakeID = 0) OR (@ActionToTakeID  IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6015 ActionToTakeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempActionToTakeID =@ActionToTakeID 
				  FROM dbo.LUHouseholdTransferOptions
					 WHERE  HouseholdTransferActionID= @ActionToTakeID
			
								 
				IF ((@TempActionToTakeID=0) OR (@TempActionToTakeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6018 ActionToTakeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  dbo.LUHouseholdTransferOptions
					 WHERE HouseholdTransferActionID = @TempActionToTakeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6013 DELETE Fail LUHouseholdTransferOptions';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [dbo].[pDeleteHousingStatus]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUHousingStatus
Description: Deletes from LUHousingStatus
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteHousingStatus](
	@HousingStatusID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempHousingStatusID int
	
	SET @TempHousingStatusID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@HousingStatusID = 0) OR (@HousingStatusID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60085 HousingStatusID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempHousingStatusID =HousingStatusID
				  FROM person.LUHousingStatus
					 WHERE  HousingStatusID= @HousingStatusID
			
								 
				IF ((@TempHousingStatusID=0) OR (@TempHousingStatusID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60088 HousingStatusID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60080';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUHousingStatus
					 WHERE HousingStatusID = @HousingStatusID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60083 DELETE Fail HousingStatus';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteIncomeSource]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUIncomeSource
Description: Deletes from LUIncomeSource
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteIncomeSource](
	@IncomeSourceID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempIncomeSourceID int
	
	SET @TempIncomeSourceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@IncomeSourceID = 0) OR (@IncomeSourceID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60095 IncomeSourceID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempIncomeSourceID = IncomeSourceID 
				  FROM person.LUIncomeSource
					 WHERE IncomeSourceID = @IncomeSourceID
			
								 
				IF ((@TempIncomeSourceID=0) OR (@TempIncomeSourceID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60098 IncomeSourceID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUIncomeSource
					 WHERE IncomeSourceID = @IncomeSourceID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60093 DELETE Fail IncomeSource';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteInsuranceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 14 March 11
*Table Name: LUInsuranceType
Description: Deletes from LUInsuranceType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteInsuranceType](
	@InsuranceTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempInsuranceTypeID int
	
	SET @InsuranceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@InsuranceTypeID = 0) OR (@InsuranceTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600015 InsuranceTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @InsuranceTypeID =InsuranceTypeID  
				  FROM person.LUInsuranceType
					 WHERE InsuranceTypeID = @InsuranceTypeID
			
								 
				IF ((@TempInsuranceTypeID=0) OR (@TempInsuranceTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600018 InsuranceTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUInsuranceType
					 WHERE InsuranceTypeID = @InsuranceTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail LuInsuranceType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [dbo].[pDeleteLanguage]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LULanguage
Description: Deletes from LULanguage
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteLanguage](
	@LanguageID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempLanguageID int
	
	SET @TempLanguageID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@LanguageID = 0) OR (@LanguageID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60065 LanguageID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempLanguageID = LanguageID 
				  FROM person.LULanguage
					 WHERE LanguageID = @LanguageID
			
								 
				IF ((@TempLanguageID=0) OR (@TempLanguageID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60068 LanguageID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LULanguage
					 WHERE LanguageID = @LanguageID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60063 DELETE Fail Language';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteLanguagesSpoken]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LanguagesSpoken
Description: Deletes from LanguagesSpoken. A person may have 1 to may records here. Deletes only one based
on input ID.
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteLanguagesSpoken](
	@PersonID int,
	@LanguagesSpokenID int, --This is the key. do not confuse with LanguageID
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempLanguagesSpokenID int
	
	SET @TempLanguagesSpokenID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@LanguagesSpokenID = 0) OR (@LanguagesSpokenID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '11005 LanguagesSpokenID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				  
				  IF ((@PersonID = 0) OR (@PersonID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '11006 PersonID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				--This just avoids deleting a LanguagesSpokenID if it is associated with a different PersonID
				SELECT @TempLanguagesSpokenID =  LanguagesSpokenID
				  FROM person.LanguagesSpoken
					 WHERE  PersonID= @PersonID AND LanguagesSpokenID = @LanguagesSpokenID
			
								 
				IF ((@TempLanguagesSpokenID=0) OR (@TempLanguagesSpokenID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -11008 LanguagesSpokenID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -11010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LanguagesSpoken
					 WHERE LanguagesSpokenID = @LanguagesSpokenID AND PersonID = @PersonID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-11013 DELETE Fail LanguagesSpoken';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteLUFamilyRelationship]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUFamilyRelationship
Description: Deletes from LUFamilyRelationship
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteLUFamilyRelationship](
	@FamilyRelationshipID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempFamilyRelationshipID int
	
	SET @TempFamilyRelationshipID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@FamilyRelationshipID = 0) OR (@FamilyRelationshipID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '60045 FamilyRelationshipID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempFamilyRelationshipID =FamilyRelationshipID
				  FROM person.LUFamilyRelationship
					 WHERE  FamilyRelationshipID= @FamilyRelationshipID
			
								 
				IF ((@TempFamilyRelationshipID=0) OR (@TempFamilyRelationshipID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -60048 FamilyRelationshipID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -60040';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUFamilyRelationship
					 WHERE FamilyRelationshipID = @FamilyRelationshipID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60043 DELETE Fail FamilyRelationship';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeletePersonType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUPersonType
Description: Deletes from LUPersonType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeletePersonType](
	@PersonTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPersonTypeID int
	
	SET @TempPersonTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@PersonTypeID = 0) OR (@PersonTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600015 PersonTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempPersonTypeID =PersonTypeID  
				  FROM person.LUPersonType
					 WHERE PersonTypeID = @PersonTypeID
			
								 
				IF ((@TempPersonTypeID=0) OR (@TempPersonTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600018 PersonTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600010';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUPersonType
					 WHERE PersonTypeID = @PersonTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600013 DELETE Fail PersonType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeletePhoneType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUPhoneType
Description: Deletes from LUPhoneType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeletePhoneType](
	@PhoneTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPhoneTypeID int
	
	SET @TempPhoneTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@PhoneTypeID = 0) OR (@PhoneTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '600085 PhoneTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempPhoneTypeID =PhoneTypeID  
				  FROM person.LUPhoneType
					 WHERE PhoneTypeID = @PhoneTypeID
			
								 
				IF ((@TempPhoneTypeID=0) OR (@TempPhoneTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -600088 PhoneTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -600080';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUPhoneType
					 WHERE PhoneTypeID = @PhoneTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600083 DELETE Fail PhoneType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeletePostalCode]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUPostalCode
Description: Deletes from LUPostalCode
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeletePostalCode](
	@PostalCodeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPostalCodeID int
	
	SET @TempPostalCodeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@PostalCodeID = 0) OR (@PostalCodeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6075 PostalCodeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempPostalCodeID =PostalCodeID
				  FROM person.LUPostalCode
					 WHERE  PostalCodeID= @PostalCodeID
			
								 
				IF ((@TempPostalCodeID=0) OR (@TempPostalCodeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6078 PostalCodeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6070';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUPostalCode
					 WHERE PostalCodeID = @PostalCodeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6073 DELETE Fail PostalCode';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteProgramServiceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUProgramServiceType
Description: Deletes from LUProgramServiceType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteProgramServiceType](
	@ProgramServiceTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempProgramServiceTypeID int
	
	SET @TempProgramServiceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ProgramServiceTypeID = 0) OR (@ProgramServiceTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6055 ProgramServiceTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempProgramServiceTypeID =ProgramServiceTypeID
				  FROM person.LUProgramServiceType
					 WHERE  ProgramServiceTypeID= @ProgramServiceTypeID
			
								 
				IF ((@TempProgramServiceTypeID=0) OR (@TempProgramServiceTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6058 ProgramServiceTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6050';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUProgramServiceType
					 WHERE ProgramServiceTypeID = @ProgramServiceTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6053 DELETE Fail ProgramServiceType';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteProgramType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUProgramType
Description: Deletes from LUProgramType
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteProgramType](
	@ProgramTypeID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempProgramTypeID int
	
	SET @TempProgramTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@ProgramTypeID = 0) OR (@ProgramTypeID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6045 ProgramTypeID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempProgramTypeID =ProgramTypeID
				  FROM person.LUProgramType
					 WHERE  ProgramTypeID= @ProgramTypeID
			
								 
				IF ((@TempProgramTypeID=0) OR (@TempProgramTypeID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6048 ProgramTypeID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6040';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUProgramType
					 WHERE ProgramTypeID = @ProgramTypeID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6043 DELETE Fail PostalCode';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteRace]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LURace
Description: Deletes from LURace
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteRace](
	@RaceID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempRaceID int
	
	SET @TempRaceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@RaceID = 0) OR (@RaceID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6025 RaceID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempRaceID =RaceID
				  FROM person.LURace
					 WHERE  RaceID= @RaceID
			
								 
				IF ((@TempRaceID=0) OR (@TempRaceID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6028 RaceID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6020';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LURace
					 WHERE RaceID = @RaceID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6023 DELETE Fail Race';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pDeleteState]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUState
Description: Deletes from LUState
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pDeleteState](
	@StateID int,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempStateID int
	
	SET @TempStateID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		
	
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@StateID = 0) OR (@StateID IS NULL)) 
				  BEGIN
					SELECT @ErrorStatus = '6035 StateID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				
				SELECT @TempStateID =StateID
				  FROM person.LUState
					 WHERE  StateID= @StateID
			
								 
				IF ((@TempStateID=0) OR (@TempStateID IS  NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -6038 StateID does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6030';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				 DELETE FROM  Person.LUState
					 WHERE StateID = @StateID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6033 DELETE Fail State';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pInsertAddress]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
* Stored Procedure Template. Change XXX in name to the name of the table that will get the insert. This is to be used
*for single table inserts only. 
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Address
Description: Inserts data to Address table.This table has the possibility of duplicate rows because
	persons can have more than one address. We can check to see if an address is a duplicate, but that will have
	limited use since we would have to count on a combination of free-format fields since it is possible to have more than
	one address in the same city, zipcode, state, county, etc.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertAddress](
	@PersonID int,
	@AddressLine1 Nvarchar(60),
	@AddressLine2 Nvarchar(60) = NULL,
	@City NVarchar(30),
	@County NVarchar(30),
	@State NVarchar(2),
	@PostalCode NVarchar(10) ,
	@AddressTypeID int,
	@ModifiedBy Name,
	@NewAddressID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempAddressTypeID int,
	@TempPersonID int,
	@TempAddressID int
	
	SET @TempAddressTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempAddressID =0;
	SET @TempAddressID = 0;		



		BEGIN TRY
		  BEGIN TRANSACTION;
				/****************************************************************************/
			--This is a bit different than some procedures because there is a lookup table associated with 
			--the address, so we need to be sure that the data matches an address type before continuing.
			SELECT @TempAddressTypeID = AddressTypeID 
			  FROM person.LUAddressType
				 WHERE AddressTypeID = (@AddressTypeID)
			
			If @TempAddressTypeID = 0
			BEGIN
				SET @ErrorStatus = ' -7002 Address Type does not existLUAddressType'; --Failed in lookup table
				RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
				
			END	
		/****************************************************************************/	          

			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-7000';
				SET @Success = 0;
				RAISERROR (@ErrorStatus,16,1);
			END
			
			  INSERT Person.Address(PersonID,AddressLine1,AddressLine2,City,County,Address.State,PostalCode,AddressTypeID,ModifiedDate, ModifiedBy)
					VALUES (@PersonID, @AddressLine1, @AddressLine2,@City,@County,@State,@PostalCode,@AddressTypeID,SYSDATETIME(),@ModifiedBy)
				
				set @NewAddressID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			 --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			 
			 SELECT @ErrorStatus =@ErrorStatus + ' -7001' +' Insert Failed';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertAddressType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUAddressType
Description: Inserts data to LUAddressType. This table matches the address with an address type
Revisions:
G.S. - 20 Oct 10. Fixed problem with error handler not firing on preliminary lookup.
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertAddressType](
	@AddressType Nvarchar(10),
	@ModifiedBy Name,
	@NewAddressTypeID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

BEGIN
	DECLARE
	@TempAddressTypeID int
	
	SET @TempAddressTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		
	

		BEGIN TRY
			BEGIN TRANSACTION;
		
			/****************************************************************************/
				--Avoid Duplicate Rows! However, a typo on input such as 'Hmoe' instead of 'Home' will do an isert.
				--Can't avoid finger problems!
				
			SELECT @TempAddressTypeID = AddressTypeID 
			  FROM person.LUAddressType
				 WHERE AddressType = Rtrim(Ltrim(@AddressType)) --Be a bit paranoid and trim the input for white spaces
			If @TempAddressTypeID <> 0 --Already Exists
				BEGIN
					SELECT @ErrorStatus = '-7015 AddressType Already Exists';
					SET @Success =0;
					RAISERROR(@ErrorStatus, 16, 1);
				END

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

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = Convert (nVarchar(50),@@ERROR) + ' -6010';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16, 1);
	END
	 
			
			  INSERT Person.LUAddressType(AddressType,ModifiedDate, ModifiedBy)
					VALUES (@AddressType,SYSDATETIME(),@ModifiedBy)
				
				set @NewAddressTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus ='';
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
		
			  SET @Success =0;
			  SELECT  @ErrorStatus = @ErrorStatus + 'Rollback -6011';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		

END







GO
/****** Object:  StoredProcedure [dbo].[pInsertCertificationText]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








/*************************************************************************************************
*Author: Gary Savard
*Date: 03/29/2011
*Table Name: LuCertificationText
Description: Inserts data to LUCertificationText.
The text inserted into this table shall not be deleted because the text history must be assoicated with signature history. No
delete SP will be created for this table.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertCertificationText](
	@CertificationText NVarchar(MAX),
	@GuidelinesText NVarchar(MAX),
	@ModifiedBy Name,
	@NewCertificationTextID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCertificationTextID int
	
	SET @TempCertificationTextID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
		
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			

			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60050';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
			  INSERT Foodshelf.LUCertificationText(CertificationText,GuidelinesText, ModifiedDate,ModifiedBy)
					VALUES (@CertificationText,@GuidelinesText,SYSDATETIME(),@ModifiedBy)
				
				set @NewCertificationTextID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60051 Insert Failed on LUCertificationText ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END












GO
/****** Object:  StoredProcedure [dbo].[pInsertCity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUCity
Description: Inserts data to LUCity.
Ideally we would have information on the county as well as the state before we add the city. However, 
we cannot assume that we have a county, so we will have it to default to 0, if no value is entered.
Revisions:
GS 20 Oct fixed failure in error handler due to implicit conversion of @@Error, worked intermittantly 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertCity](
	@CityName NVarchar(30),
	@CityAbbreviation Nvarchar(30) ='',
	@StateID int,
	@CountyID int = 0,--Default countyID to 0 just in case it comes in later. 
	@PostalCodeID int =0, --Will come later, just a place holder
	@ModifiedBy Name,
	@NewCityID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCityID int
	
	SET @TempCityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
		
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			IF @StateID = 0 --Must have a state before we can have a city!
				BEGIN
					SELECT @ErrorStatus =  '-60055 StateID cant be NULL or 0';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
	
/****************************************************************************/

			SELECT @TempCityID = CityID 
				FROM person.LUCity
					WHERE CityName = Rtrim(Ltrim(@CityName)) and StateID = @StateID
	     		If @TempCityID <>0 
					BEGIN
						SET @ErrorStatus = ' -60052 City exists in LUCity'; 
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
		
					END	

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

			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60050';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
			  INSERT Person.LUCity(StateID,CountyID,PostalCodeID,CityName,CityAbbreviation, ModifiedDate,ModifiedBy)
					VALUES (@StateID,@CountyID,@PostalCodeID,@CityName,@CityAbbreviation,SYSDATETIME(),@ModifiedBy)
				
				set @NewCityID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60051 Insert Failed on City ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertClientFamilyRecord]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		Gary Savard
-- Create date: 26 Oct 2010
-- Description:	This is the main stored procedure to save a new family member for a client
-- into the system. It calls several other stored procedures to do inserts into 
-- selected parts of the DB. Clients and Family members of clients have similar data, but 
--will use separate stored procedures for clarity.
--FOOD. Same idea with the rest of the programs.
--IDs that are important such as 'address type' from that lookup table need to be passed in here since they
--were selected by the user. No need to try to figure them out in the SP
--Certification has its own button so we have a separate stored procedure to deal with that functionality and the same for 
--family members since they do not have some of the information that we need for the client. 

--Revisions: 4 Nov 10- Added Client notes insert procedure call
--15 March 11. Modified to remove address, phone, email and number in household for family members. The version with all of these parameters
--exists in a new stored procedure called pInsertFamilyRecordWithAddress, if ever needed. It is the same sp as this one before these edits.
--5 April remove @numberInHousehold, @HomeboundDelivery,@ISPrimaryLanguage,@LanguageId,@Title,@Suffix
--19 July 2011 Added LTRIM,RTRIM for @Firstname, @MiddleName, @LastName
-- =============================================
CREATE PROCEDURE [dbo].[pInsertClientFamilyRecord] (
	@RecordSource NVarchar(8),
	@ClientPersonID int,
  	@FirstName Name,
	@MiddleName Name = NULL,
	@LastName Name,
	@DateOfBirth DateTime,
	@RelationshipID int,
	@RelationshipDescription NVarchar(50)='',
	@HousingStatus nVarchar(50),--The TEXT value from the lookup table. Saves having to query by ID later
	@FamilyStatusType NVarchar(50),
	@Disability NoYesMaybe =0,
	@Gender NVarchar(2)='',--Foodshelf and WX may leave blank
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe =0 ,
	@InsuranceType NVarchar(50),
	@FoodStamps NoYesMaybe =0,--Three squares
	@EducationCategoryID int =0, --Not required for Food shelf
	@CountryOfOrigin nVarchar(70)='', --Not required for food shelf
	@Race NVarchar(20) =NULL,
	@Ethnicity NVarchar(20) =NULL, 
	@IncomeSourceID int =0,
	@Notes NVarchar(MAX)=NULL,--A single person may have many notes. The notes will be specific to a particular program, so we will not have a single notes table
	@ModifiedBy Name,
	@NewPersonIDout int Output,
	@NewFamilyRelationshipID int output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
	

SET NOCOUNT ON;
	DECLARE
	@ValidSource int,
	@NewPersonID int,
	@NewAddressID int,
	@NewPhoneID int,
	@Succ bit,
	@ErrorMsg NVarchar(50),
	@NewDemographicsID int, --Not using here, just a place holder!
	@NewFoodTypeGivenID int, -- We don't do anything with this. Just receives SP output for now.
	@NewClientNotesID int,
	@TempClientPersonID int,
	@DummyNumberInHousehold int, --just place holder with default of 0
	@DummyHomeboundDelivery int,
	@DummyIsPrimaryLanguage bit,
	@DummyLanguageID int,
	@DummyTitle NVarchar(8),
	@DummySuffix NVarchar(10)
		
	
	SET @ValidSource =0;
	SET @NewPersonID =0;
	SET @NewAddressID =0;
	SET @NewPhoneID = 0;
	SET @NewDemographicsID =0;
	SET @NewFoodTypeGivenID =0;
	SET @NewClientNotesID =0;
	SET @Succ =0;
	SET @ErrorMsg ='';
	SET @TempClientPersonID =0;
	SET @DummyNumberInHousehold =0;
	SET @DummyHomeboundDelivery=2;--This is set to N/A
	SET @DummyIsPrimaryLanguage=0;
	SET @DummyLanguageID=0;
	SET @DummyTitle = NULL;
	SET @DummySuffix = NULL;
	SET @FirstName = LTRIM(rtrim(@firstname));
	SET @MiddleName = LTRIM(RTRIM(@MiddleName));
	SET @LastName = LTRIM(RTRIM(@LastName));
		
 BEGIN TRY
	BEGIN TRANSACTION;
	
	--The family member must be associated with a ClientPersonID or we bail.
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
		IF @ClientPersonID = 0 OR @ClientPersonID IS NULL
			BEGIN  --IF @ClientPersonID = 0 OR 
				SET @Success =0;
				SET @ErrorStatus = '-17500 ClientPersonID cannot be null or 0';
				RAISERROR(@ErrorStatus,16,1);
			
			END	--IF @ClientPersonID = 0 OR 
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++				
		SELECT @TempClientPersonID = @ClientPersonID
			FROM Person.Person
				WHERE PersonID = @ClientPersonID
				
		IF @TempClientPersonID = 0 OR @TempClientPersonID IS NULL--the client must exist to have a family member!
			BEGIN --IF @TempClientPersonID = 0 OR
				SET @Success=0;
				SET @ErrorStatus = '-17501 ClientPersonID does not exist in person';
				RAISERROR (@ErrorStatus,16,1);
			END  --IF @TempClientPersonID = 0 OR
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++				
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++		
	--Take the return value and throw error if 0 because we cannot proceed of we don't know
	--which set of sps to call.
	SET @ValidSource = DBO.ValidateDataSource(@RecordSource);
	
	IF @ValidSource =0
		BEGIN --IF @ValidSource =0
			SET @Success =0;
			SELECT @ErrorStatus = '-17100 Invalid Record source';
			RAISERROR(@ErrorStatus,16,1);
			--Raise Error Here because the source is unknown.
		END --IF @ValidSource =0
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++					
	
	BEGIN --Insert into Person and take the new personID for further use. Email address NULL and Email Contact 0 hard coded for family members	
		EXEC DBO.pInsertPerson @DummyTitle,@FirstName,@MiddleName,@LastName,@DummySuffix, @DateOfBirth,NULL,0,@ModifiedBy,@NewPersonID Output,@Succ Output, @ErrorMsg Output;
		SET @NewPersonIDout = @NewPersonID;--Fix this in future!
		
		
		IF @Succ =0 -- Failure!
			BEGIN  --IF @Succ =0 -- Failure!
				SET @Success = @Succ;
				SELECT @ErrorStatus = '-17200 Sub Pro pInsertPerson Fail'+ @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
			END --IF @Succ =0 -- Failure!
		SET @Success =1;
		SET @ErrorStatus='';	
	END --Insert into Person and take the new personID for further use.	
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
IF @NewPersonID > 0 AND @NewPersonID IS NOT NULL 
  BEGIN --IF @NewPersonID > 0 AND @NewPersonID IS NOT NULL 
			
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++		
	--Insert Demographics
		BEGIN --Insert Demographics. Number in household hard coded to 0 for family members
			EXEC dbo.pInsertDemographics @NewPersonID,@EducationCategoryID ,@HousingStatus,@DummyNumberInHousehold,@Gender,@Race,@CountryOfOrigin,@Ethnicity,@Disability,@CSFP,@Veteran,@HealthInsurance,@FamilyStatusType,@InsuranceType,@FoodStamps,@DummyHomeboundDelivery,@ModifiedBy,@NewDemographicsID OUTPUT,@Succ OUTPUT, @ErrorMsg OUTPUT; 
		
				IF @Succ = 0
					BEGIN --IF @Succ = 0
						SET @Success =0;
						SELECT @ErrorStatus ='-13200 Sub proc Demographics returned fail' + @ErrorMsg;
						RAISERROR(@ErrorStatus,16,1);
						
					END --IF @Succ = 0
				END --Insert Demographics
			
			--Insert income source. This may take multiple entries in the future so we have not created an SP yet.	
			IF @IncomeSourceID <> 0
				BEGIN	
					INSERT INTO PERSON.Income (IncomeSourceID,PersonID,ModifiedBy,ModifiedDate) Values (@IncomeSourceID,@NewPersonID,@ModifiedBy,SYSDATETIME())
					
				END	
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SET @ErrorStatus = 'Fail on Insert Income';
					RAISERROR (@ErrorSTatus,16,1) with log;
				END	
		
			--Insert Client Notes if they exist. This insert procedure is for the client, so we do not have
			--A value for HouseholdMemberPersonID so we hard code it to 0.
				IF LTRIM(RTRIM(@notes))<>'' AND @Notes IS NOT NULL
					BEGIN --IF LTRIM(RTRIM(@notes))<>''
						EXEC DBO.pInsertHouseholdNotes @ClientPersonID, @NewPersonID,@Notes,@ModifiedBy,@NewClientNotesID OUTPUT,@Succ OUTPUT,@ErrorMsg OUTPUT;
						IF @Succ =0
							BEGIN --IF @Succ =0
								SET @Success =0
								SET @ErrorStatus = '-17001 Insert Failed Notes' + @ErrorMsg;
								RAISERROR(@ErrorStatus,16,1);
							END --IF @Succ =0
					
					END --IF LTRIM(RTRIM(@notes))<>''
		
	--We have everything except for the relationship to the client, so we do that last.
	 
		
			EXEC DBO.pInsertFamilyRelationship @NewPersonIDout, @ClientPersonID,@RelationshipID,@RelationshipDescription,@ModifiedBy, @NewFamilyRelationshipID OUTPUT, @Succ OUTPUT, @ErrorMsg OUTPUT; 
			IF @Succ =0
				BEGIN --IF @Succ =0
					SET @Success =0;
					SET @ErrorStatus ='-17001 Insert Failed Family Relationship'+ @ErrorMsg
					RAISERROR(@ErrorStatus,16,1);
				END	--IF @Succ =0
					
	--We are using nested transactions to make sure one exists in case 
	--of a rollback in subordinate Stored Procedure
	IF @@TRANCOUNT > 0 
		BEGIN --IF @@TRANCOUNT > 0 
		 SET @Success =1;
		 SET @ErrorStatus ='';
			COMMIT TRANSACTION;
		END --IF @@TRANCOUNT > 0 
END --IF @NewPersonID > 0 AND @NewPersonID IS NOT NULL 
END TRY
	
BEGIN CATCH
	IF @@TRANCOUNT >0
		BEGIN
		SET @Success =0
		SET @ErrorStatus =@ErrorStatus + '  ' +@@Error
			ROLLBACK TRANSACTION;
			
		RAISERROR(@ErrorStatus,16,1);
		END
END CATCH

 
    
	















GO
/****** Object:  StoredProcedure [dbo].[pInsertClientFamilyRecordWithAddress]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










-- =============================================
-- Author:		Gary Savard
-- Create date: 26 Oct 2010
-- Description:	This is the main stored procedure to save a new family member for a client
-- into the system. It calls several other stored procedures to do inserts into 
-- selected parts of the DB. Clients and Family members of clients have similar data, but 
--will use separate stored procedures for clarity.
--FOOD. Same idea with the rest of the programs.
--IDs that are important such as 'address type' from that lookup table need to be passed in here since they
--were selected by the user. No need to try to figure them out in the SP
--Certification has its own button so we have a separate stored procedure to deal with that functionality and the same for 
--family members since they do not have some of the information that we need for the client. 

--Revisions: 4 Nov 10- Added Client notes insert procedure call

-- 16 March 11. This stored procedure has been renamed from pInsertClientFamilyRecord to pInsertClientFamilyRecordWithAddress
--Champlain Charity does not want to collect addresses of family members other than the client. The new pInsertClientFamilyRecord does not collect that data. This 
--is kept in case future clients want to capture that data.


-- =============================================
CREATE PROCEDURE [dbo].[pInsertClientFamilyRecordWithAddress] (
	@RecordSource NVarchar(8),
	@ClientPersonID int,
    @Title NVarchar(8) =NULL,
	@FirstName Name,
	@MiddleName Name = NULL,
	@LastName Name,
	@Suffix NVarchar(10) = NULL,
	@DateOfBirth DateTime,
	@RelationshipID int,
	@RelationshipDescription NVarchar(50)='',
	@Address1 NVarchar(60) =NULL,--Only for Foodshelf!!
	@Address2 NVarchar(60) = NULL,
	@City	NVarchar(30),
	@County NVarchar(30) = NULL,
	@State NVarchar(2),
	@PostalCode NVarchar(10),
	@AddressTypeID int =0,--From the Lookup based on user input. May not need if Foodshelf
	@EmailAddress Nvarchar(50) = NULL,--May not need for foodshelf
	@EmailContactPreference NoYes =0,
	@PhoneNumber Phone ='',
	@PhoneExtension Nvarchar(8) ='', --may not be implemented yet
	@PhoneTypeID int =0, --0 default, Food shelf again!
	@HousingStatus nVarchar(50),--The TEXT value from the lookup table. Saves having to query by ID later
	@NumberInHousehold int,
	@Disability NoYesMaybe =0,
	@Gender NVarchar(2)='',--Foodshelf and WX may leave blank
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe =0 ,
	@FoodStamps NoYesMaybe =0,--Three squares
	@HomeboundDelivery NoYesMaybe =0,
	@LanguageID int =0,--This is only important for volunteers and that funtionality has not been developed yet.
	@IsPrimaryLanguage bit =0,
	@EducationCategoryID int =0, --Not required for Food shelf
	@CountryOfOrigin nVarchar(70)='', --Not required for food shelf
	@Race NVarchar(20) =NULL,
	@Ethnicity NVarchar(20) =NULL, 
	@IncomeSourceID int =0,
	@Notes NVarchar(MAX)=NULL,--A single person may have many notes. The notes will be specific to a particular program, so we will not have a single notes table
	@ModifiedBy Name,
	@NewPersonIDout int Output,
	@NewFamilyRelationshipID int out,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
	

SET NOCOUNT ON;
	DECLARE
	@ValidSource int,
	@NewPersonID int,
	@NewAddressID int,
	@NewPhoneID int,
	@Succ bit,
	@ErrorMsg NVarchar(50),
	@NewDemographicsID int, --Not using here, just a place holder!
	@NewFoodTypeGivenID int, -- We don't do anything with this. Just receives SP output for now.
	@NewClientNotesID int,
	@TempClientPersonID int
		
	
	SET @ValidSource =0;
	SET @NewPersonID =0;
	SET @NewAddressID =0;
	SET @NewPhoneID = 0;
	SET @NewDemographicsID =0;
	SET @NewFoodTypeGivenID =0;
	SET @NewClientNotesID =0;
	SET @Succ =0;
	SET @ErrorMsg ='';
	SET @TempClientPersonID =0;
	SET @FirstName =LTRIM(RTRIM(@FirstName));
	SET @MiddleName = LTRIM(RTRIM(@MiddleName));
	SET @LastName = LTRIM(RTRIM(@LastName));
		
 BEGIN TRY
	BEGIN TRANSACTION;
	
	--The family member must be associated with a ClientPersonID or we bail.
	
		IF @ClientPersonID = 0 OR @ClientPersonID IS NULL
			BEGIN
				SET @Success =0;
				SET @ErrorStatus = '-17500 ClientPersonID cannot be null or 0';
				RAISERROR(@ErrorStatus,16,1);
			
			END	
			
		SELECT @TempClientPersonID = @ClientPersonID
			FROM Person.Person
				WHERE PersonID = @ClientPersonID
				
		IF @TempClientPersonID = 0 OR @TempClientPersonID IS NULL--the client must exist to have a family member!
			BEGIN
				SET @Success=0;
				SET @ErrorStatus = '-17501 ClientPersonID does not exist in person';
				RAISERROR (@ErrorStatus,16,1);
			END
			
	
	--Take the return value and throw error if 0 because we cannot proceed of we don't know
	--which set of sps to call.
	SET @ValidSource = DBO.ValidateDataSource(@RecordSource);
	
	IF @ValidSource =0
		BEGIN
			SET @Success =0;
			SELECT @ErrorStatus = '-17100 Invalid Record source';
			RAISERROR(@ErrorStatus,16,1);
			--Raise Error Here because the source is unknown.
		END
				
	--Insert into Person and take the new personID for further use.	
	BEGIN
		EXEC DBO.pInsertPerson @Title,@FirstName,@MiddleName,@LastName,@Suffix, @DateOfBirth,@EmailAddress,@EmailContactPreference,@ModifiedBy,@NewPersonID Output,@Succ Output, @ErrorMsg Output;
		SET @NewPersonIDout = @NewPersonID;
		
		
		IF @Succ =0 -- Failure!
			BEGIN
				SET @Success = @Succ;
				SELECT @ErrorStatus = '-17200 Sub Pro Fail'+ @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
			END
		SET @Success =1;
		SET @ErrorStatus='';	
	END
	
	--IF the source is from Food Shelf we cannot assume that we will need to call the address or phone SPs because they 
	--are not required to take that information.
	--IF we have a good PersonID returned, we continue to Address
	
	--The address should be the same as that of the client, but we will add it anyway because this person
	--may eventually become a client and we will already have an AddressID that we can use and modify the location.

		IF @NewPersonID > 0 AND @NewPersonID IS NOT NULL 
		BEGIN
			IF ((@RecordSource <> 'FOOD') AND (LTRIM(RTRIM(@Address1)) ='') OR (LTRIM(RTRIM(@Address1)) IS NULL) )--This is a problem because address is required
				BEGIN
					SET @Succ =0;
					SET @ErrorStatus ='-17300 Address Required for Non foodshelf intake.';
					RAISERROR(@ErrorStatus,16,1);
				END
		IF ((LTRIM(RTRIM(@Address1)) <> '') AND (@Address1 IS NOT NULL)) OR @RecordSource = 'FOOD'
		 BEGIN	
			EXEC DBO.pInsertAddress @NEWPersonID, @Address1,@Address2, @City,@County,@State,@PostalCOde,@AddressTypeID,@ModifiedBy, @NewAddressID Output,@Succ Output, @ErrorMsg Output ;	
			
			IF @Succ =0 --Failed, Rollback!
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-17200 Sub proc call returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1);
				END
				
		END

	
	--Insert Phone Number
	--We allow phone number since they may have a cell.
	BEGIN
		IF ((@RecordSource <> 'FOOD') AND (LTRIM(RTRIM(@PhoneNumber)) ='') OR (LTRIM(RTRIM(@PhoneNumber)) IS NULL) )--This is a problem because Phone Number is required
			BEGIN
						SET @Succ =0;
						SET @ErrorStatus ='-17400 Phone Number Required for Non foodshelf intake.';
						RAISERROR(@ErrorStatus,16,1);
			END
			
		IF (LTRIM(RTRIM(@PhoneNumber))<>'' AND @PhoneNumber IS NOT NULL)
			BEGIN
				EXEC DBO.pInsertPhone @NewPersonID,@PhoneNumber, @PhoneExtension,@PhoneTypeID,@ModifiedBy,@NewPhoneID output, @Succ output, @ErrorMsg output ;
			END
			
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc Phone returned fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1);
				END
	END
	
	--Insert Demographics
	BEGIN
		EXEC dbo.pInsertDemographics @NewPersonID,@EducationCategoryID ,@HousingStatus,@NumberInHousehold,@Gender,@Race,@CountryOfOrigin,@Ethnicity,@Disability,@CSFP,@Veteran,@HealthInsurance,@FoodStamps,@HomeboundDelivery,@ModifiedBy,@NewDemographicsID OUTPUT,@Succ OUTPUT, @ErrorMsg OUTPUT; 
		
		IF @Succ = 0
			BEGIN
				SET @Success =0;
				SELECT @ErrorStatus ='-13200 Sub proc Demographics returned fail' + @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
				
			END
		END
		
	--Insert Client Notes if they exist. This insert procedure is for the client, so we do not have
	--A value for HouseholdMemberPersonID so we hard code it to 0.
		IF LTRIM(RTRIM(@notes))<>'' AND @Notes IS NOT NULL
			BEGIN
				EXEC DBO.pInsertHouseholdNotes @ClientPersonID, @NewPersonID,@Notes,@ModifiedBy,@NewClientNotesID OUTPUT,@Succ OUTPUT,@ErrorMsg OUTPUT;
				IF @Succ =0
				BEGIN
					SET @Success =0
					SET @ErrorStatus = '-17001 Insert Failed Notes' + @ErrorMsg;
					RAISERROR(@ErrorStatus,16,1);
				END
			
			END
		
	--We have everything except for the relationship to the client, so we do that last.
	 
		
			EXEC DBO.pInsertFamilyRelationship @NewPersonIDout, @ClientPersonID,@RelationshipID,@RelationshipDescription,@ModifiedBy, @NewFamilyRelationshipID OUTPUT, @Succ OUTPUT, @ErrorMsg OUTPUT; 
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SET @ErrorStatus ='-17001 Insert Failed Family Relationship'+ @ErrorMsg
					RAISERROR(@ErrorStatus,16,1);
				END	
		
			
	

		
	--We are using nested transactions to make sure one exists in case 
	--of a rollback in subordinate Stored Procedure
	IF @@TRANCOUNT > 0 
		BEGIN
		 SET @Success =1;
		 SET @ErrorStatus ='';
			COMMIT TRANSACTION;
		END
END
END TRY
	
BEGIN CATCH
	IF @@TRANCOUNT >0
		BEGIN
		SET @Success =0
		SET @ErrorStatus =@ErrorStatus + '  ' +@@Error
		Set @ErrorStatus = @ErrorStatus + 'Failure in pInsertClientFamilyRecordWithAddress'
		ROLLBACK TRANSACTION;
			
		RAISERROR(@ErrorStatus,16,1);
		END
END CATCH

 
    
	












GO
/****** Object:  StoredProcedure [dbo].[pInsertClientRecord]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO















-- =============================================
-- Author:		Gary Savard
-- Create date: 26 Oct 2010
-- Description:	This is the main stored procedure to save a new client
-- into the system. It calls several other stored procedures to do inserts into 
-- selected parts of the DB. Clients and Family members of clients have similar data, but 
--will use separate stored procedures for clarity.
--@RecordSource can be FOOD,WX,MICRO,TENANT,COMMACT,ADMIN. This will be used to only execute parts of the 
--SP relevant to the client intake data brought in. For example, Foodshelf requires that a record be 
--set for the type of food taken, but this is not required elsewhere so we only execute that SP If things come from 
--FOOD. Same idea with the rest of the programs.
--IDs that are important such as 'address type' from that lookup table need to be passed in here since they
--were selected by the user. No need to try to figure them out in the SP
--Certification has its own button so we have a separate stored procedure to deal with that functionality and the same for 
--family members since they do not have some of the information that we need for the client. 

--Revisions: 4 Nov 10- Added Client notes insert procedure call

---14 March 11 Added functionality for Cell Phone, Mailing Address, FamilyStatus, InsuranceType
--19 April, Add @IsUpdateBreadGroceries parameter to avoid inserting bread/produce, groceries if this is not required.
--3 May 11, fixed mail address blank records.
--11 July 11, Added LTrim,RTRIM @FIRSTNAME, @MiddleName, @LastName
-- =============================================
CREATE PROCEDURE [dbo].[pInsertClientRecord] (
	@RecordSource NVarchar (8), --This allows for the sub sp's to be executed or skipped based on what data is to be saved
	@Title NVarchar(8) =NULL,
	@FirstName Name,
	@MiddleName Name = NULL,
	@LastName Name,
	@Suffix NVarchar(10) = NULL,
	@Gender NVarchar(2) ='',--May not need everywhere
	@DateOfBirth DateTime,
	@PhysicalAddress1 NVarchar(60) =NULL,--Only for Foodshelf!!
	@PhysicalAddress2 NVarchar(60) = NULL,
	@PhysicalCity	NVarchar(30),
	@PhysicalCounty NVarchar(30) = NULL,
	@PhysicalState NVarchar(2),
	@PhysicalPostalCode NVarchar(10),
	@PhysicalAddressTypeID int=0,--This is just addressTypeID, but this name is used to make distinctive in parameters list
	@MailAddress1 NVarchar(60) = NULL,
	@MailAddress2 NVarchar(60)= NULL,
	@MailCity NVarchar(30)=NULL,
	@MailCounty NVarchar(30)=NULL,
	@MailState NVarchar(2) =NULL,
	@MailPostalCode NVarchar(10)=NULL,
	@MailAddressTypeID int =0,--From the Lookup based on user input. May not need if Foodshelf
	@EmailAddress Nvarchar(50) = NULL,
	@EmailContactPreference NoYes =0,
	@PhoneNumber Phone ='',
	@PhoneExtension Nvarchar(8) ='', --may not be implemented yet
	@PhoneTypeID int =0, --Food shelf again!
	@PhoneNumber2 Phone ='',
	@PhoneExtension2 Nvarchar(8)='',
	@PhoneTypeID2 int =0,
	@FamilyStatusType Nvarchar(50), 
	@HousingStatus nVarchar(50),--The TEXT value from the lookup table. Saves having to query by ID later
	@Disability NoYesMaybe =0,
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe =0 ,
	@InsuranceType Nvarchar(50),
	@FoodStamps NoYesMaybe =0,--Three squares
	@HomeboundDelivery NoYesMaybe =0,
	@LanguageID int =0,--This is only important for volunteers and that funtionality has not been developed yet.
	@IsPrimaryLanguage bit =0,
	@EducationCategoryID int =0, 
	@CountryOfOrigin nVarchar (70)='', 
	@Race NVarchar(20) =NULL,
	@Ethnicity NVarchar(20) =NULL, 
	@NumberInHousehold int,
	@IncomeSourceID int =0,
	@Notes NVarchar(MAX)=NULL,--A single person may have many notes. The notes will be specific to a particular program, so we will not have a single notes table
	@FoodGiven FoodShelf.GroceryOrBreadProduce,
	@FoodReceivedDate DateTime,
	@IsUpdateBreadGroceries bit, --This is 1 if there is an update for the record and bread/produce, groceries.
	@ModifiedBy Name,
	@NewPersonIDout int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
	

SET NOCOUNT ON;
	DECLARE
	@ValidSource int,
	@NewPersonID int,
	@NewPhysicalAddressID int,
	@NewMailAddressID int,
	@NewPhoneID int,
	@NewPhoneID2 int,
	@Succ bit,
	@ErrorMsg NVarchar(50),
	@NewDemographicsID int, --Not using here, just a place holder!
	@NewFoodTypeGivenID int, -- We don't do anything with this. Just receives SP output for now.
	@NewClientNotesID int,
	@NewIncomeSourceID int
	
	SET @ValidSource =0;
	SET @NewPersonID =0;
	SET @NewPhysicalAddressID =0;
	SET @NewMailAddressID =0;
	SET @NewPhoneID = 0;
	SET @NewPhoneID2 =0;
	SET @NewDemographicsID =0;
	SET @NewFoodTypeGivenID =0;
	SET @NewClientNotesID =0;
	SET @NewIncomeSourceId =0;	
	SET @Succ =0;
	SET @ErrorMsg ='';
	SET @FirstName = LTRIM(RTRIM(@FirstName));
	SET @MiddleName = LTRIM(RTRIM(@MiddleName));
	SET @LastName = LTRIM(RTRIM(@LastName));
	
BEGIN		
 BEGIN TRY
	BEGIN TRANSACTION;
	
	
	--Take the return value and throw error if 0 because we cannot proceed of we don't know
	--which set of sps to call.
	SET @ValidSource = DBO.ValidateDataSource(@RecordSource);
	
	IF @ValidSource =0
		BEGIN
			SET @Success =0;
			SELECT @ErrorStatus = '-13100 Invalid Record source';
			RAISERROR(@ErrorStatus,16,1) with log;
			--Raise Error Here because the source is unknown.
		END
		
	--Insert into Person and take the new personID for further use.	
	BEGIN
		EXEC DBO.pInsertPerson @Title,@FirstName,@MiddleName,@LastName,@Suffix, @DateOfBirth,@EmailAddress,@EmailContactPreference,@ModifiedBy,@NewPersonID Output,@Succ Output, @ErrorMsg Output;
		SET @NewPersonIDout = @NewPersonID;
		IF @Succ =0 -- Failure!
			BEGIN
				SET @Success = @Succ;
				SELECT @ErrorStatus = '-13200 Sub Pro Fail'+ @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1) with log;
			END
	END
	
	--IF the source is from Food Shelf we cannot assume that we will need to call the address or phone SPs because they 
	--are not required to take that information.
	--IF we have a good PersonID returned, we continue to Address
	

		IF @NewPersonID > 0 AND @NewPersonID IS NOT NULL 
		BEGIN
			IF (@RecordSource <> 'FOOD') AND ((LTRIM(RTRIM(@PhysicalAddress1)) ='') OR (LTRIM(RTRIM(@PhysicalAddress1)) IS NULL)) --This is a problem because address is required
				BEGIN
					SET @Succ =0;
					SET @ErrorStatus ='-13300 Address Required for Non foodshelf intake.';
					RAISERROR(@ErrorStatus,16,1) with log;
				END
		
		IF (((LTRIM(RTRIM(@PhysicalAddress1)) <> '') AND (@PhysicalAddress1 IS NOT NULL))) OR @RecordSource = 'FOOD'
		 BEGIN	
			EXEC DBO.pInsertAddress @NewPersonID, @PhysicalAddress1,@PhysicalAddress2, @PhysicalCity,@PhysicalCounty,@PhysicalState,@PhysicalPostalCOde,@PhysicalAddressTypeID,@ModifiedBy, @NewPhysicalAddressID Output,@Succ Output, @ErrorMsg Output ;	
		
			IF @Succ =0 --Failed, Rollback!
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc PhyAddr call returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1) with log;
				END
					
		END
		
		IF (((LTRIM(RTRIM(@MailAddress1)) <> '') AND (@MailAddress1 IS NOT NULL))) /*OR @RecordSource = 'FOOD' Removed. Not necessary*/
		 BEGIN	
			EXEC DBO.pInsertAddress @NewPersonID, @MailAddress1,@MailAddress2, @MailCity,@MailCounty,@MailState,@MailPostalCOde,@MailAddressTypeID,@ModifiedBy, @NewMailAddressID Output,@Succ Output, @ErrorMsg Output ;	
		
			IF @Succ =0 --Failed, Rollback!
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc MailAddr call returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1) with log;
				END
					
		END
		
		--We now need to check for a mailing address
		

	
	--Insert Phone Number
	BEGIN
		IF ((@RecordSource <> 'FOOD') AND (LTRIM(RTRIM(@PhoneNumber)) ='') OR (LTRIM(RTRIM(@PhoneNumber)) IS NULL) )--This is a problem because Phone Number is required
			BEGIN
						SET @Succ =0;
						SET @ErrorStatus ='-13400 Phone Number Required for Non foodshelf intake.';
						RAISERROR(@ErrorStatus,16,1) with log;
			END
			
		IF (LTRIM(RTRIM(@PhoneNumber))<>'' AND @PhoneNumber IS NOT NULL)
			BEGIN
				EXEC DBO.pInsertPhone @NewPersonID,@PhoneNumber, @PhoneExtension,@PhoneTypeID,@ModifiedBy,@NewPhoneID output, @Succ output, @ErrorMsg output ;
			END
			
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc Insert phone returned fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1) with log;
				END
	END
	
	--Insert Cell Phone. This is not a required field so we do not do the same checks as with regular phone.
	IF (LTRIM(RTRIM(@PhoneNumber2))<>'' AND @PhoneNumber2 IS NOT NULL)
			BEGIN
				EXEC DBO.pInsertPhone @NewPersonID,@PhoneNumber2, @PhoneExtension2,@PhoneTypeID2,@ModifiedBy,@NewPhoneID output, @Succ output, @ErrorMsg output ;
			END
			
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc Insert Phone returned fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1) with log;
				END
	
	--Insert Demographics
	BEGIN
	  
		EXEC dbo.pInsertDemographics @NewPersonID,@EducationCategoryID ,@HousingStatus,@NumberInHousehold,@Gender,@Race,@CountryOfOrigin,@Ethnicity,@Disability,@CSFP,@Veteran,@HealthInsurance,@FamilyStatusType,@InsuranceType,@FoodStamps,@HomeboundDelivery,@ModifiedBy,@NewDemographicsID OUTPUT,@Succ OUTPUT, @ErrorMsg OUTPUT; 
		
		IF @Succ = 0
			BEGIN
				SET @Success =0;
				SELECT @ErrorStatus = '-2021 Insert Failed Demographics' + @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1) with log;
				
			END
		END
		
	--Insert Income Source. We are doing this directly but it could be put into a stored procedure. This may be modified for multiple entry later on but we assume 1 to 1 relationship a this point
	IF @IncomeSourceID <> 0
		BEGIN	
			INSERT INTO PERSON.Income (IncomeSourceID,PersonID,ModifiedBy,ModifiedDate) Values (@IncomeSourceID,@NewPersonID,@ModifiedBy,SYSDATETIME())
			
		END	
	IF @Succ =0
		BEGIN
			SET @Success =0;
			SET @ErrorStatus = 'Fail on Insert Income';
			RAISERROR (@ErrorSTatus,16,1) with log;
		END	
	--Insert Client Notes if they exist. This insert procedure is for the client, so we do not have
	--A value for HouseholdMemberPersonID so we hard code it to 0.
		IF LTRIM(RTRIM(@notes))<>'' AND @Notes IS NOT NULL
			BEGIN
				EXEC DBO.pInsertHouseholdNotes @NewPersonID, 0,@Notes,@ModifiedBy,@NewClientNotesID OUTPUT,@Succ OUTPUT,@ErrorMsg OUTPUT;
				IF @Succ =0
				BEGIN
					SET @Success =0
					SET @ErrorStatus = '-14001 Insert Failed Notes' + @ErrorMsg;
					RAISERROR(@ErrorStatus,16,1) with log;
				END
			
			END
		
	--IF source is foodshelf, we need to capture whether they were in for bread/produce or groceries 
	
	IF @RecordSource ='FOOD' and @IsUpdateBreadGroceries = 1
		BEGIN
			EXEC DBO.pInsertFoodTypeGiven @NewPersonID,@FoodReceivedDate,@FoodGiven,@ModifiedBy,@NewFoodTypeGivenID OUTPUT, @Succ OUTPUT, @ErrorMsg OUTPUT;
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus ='-600021 Insert FoodType fail' + @ErrorMsg;
					RAISERROR (@ErrorStatus,16,1) with log;
				END	
	END
		

		
	--We are using nested transactions to make sure one exists in case 
	--of a rollback in subordinate Stored Procedure
	IF @@TRANCOUNT > 0 
		BEGIN
			SET @Success = 1;
			COMMIT TRANSACTION;
		END
END
END TRY
	
BEGIN CATCH
	IF @@TRANCOUNT >0
		BEGIN
		SET @Success = 0
		SET @ErrorStatus =@ErrorStatus + '  ' +@@Error
			ROLLBACK TRANSACTION;
			
		RAISERROR(@ErrorStatus,16,1) with log;
		END
END CATCH

    -- Insert statements for procedure here
    END
    
	

















GO
/****** Object:  StoredProcedure [dbo].[pInsertContactType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUContactType
Description: Inserts data to LUContactType.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertContactType](
	@Name Nvarchar(50) ,
	@ModifiedBy Name,
	@NewContactTypeID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempNewContactID int
	
	SET @TempNewContactID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

			
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			SELECT @TempNewContactID = ContactTypeID 
			  FROM person.LUContactType
			     WHERE Name = Rtrim(Ltrim(@Name)) 
	     			If @TempNewContactID <>0 
				    	BEGIN
					     	SET @ErrorStatus = ' -60022 Contact Type already exists in LUContactType'; 
							RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
						END	
			 
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  INSERT Person.LUContactType(Name,ModifiedDate,ModifiedBy)
					VALUES (@Name,SYSDATETIME(),@ModifiedBy)
				
				set @NewContactTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60021 Insert Failed on LUContactType';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END









GO
/****** Object:  StoredProcedure [dbo].[pInsertCountryOfOrigin]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUCountryOfOrigin
Description: Inserts data to LUCountryOfOrigin.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertCountryOfOrigin](
	@CountryAbbreviation Nvarchar(30) ='',
	@CountryName Nvarchar(50),
	@FIPSCode NVarchar(2)='',
	@ModifiedBy Name,
	@NewCountryID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempNewCountryID int
	
	SET @TempNewCountryID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

	 
		
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		    SELECT @TempNewCountryID = CountryID 
			  FROM person.LUCountryOfOrigin
				 WHERE CountryName = Rtrim(Ltrim(@CountryName)) 
	     			If @TempNewCountryID <>0 
						BEGIN
							SET @ErrorStatus = ' -60032 Country already exists in LUCountryOfOrigin'; 
								RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
							
						END	
 
/****************************************************************************/	          

						IF @@Error <> 0 
						BEGIN
							SELECT @ErrorStatus = @@ERROR + '-60030';
							SET @Success = 0;
							RAISERROR(@ErrorStatus, 16,1);
						END
				  INSERT Person.LUCountryOfOrigin(CountryAbbreviation,CountryName,FIPSCode,ModifiedDate,ModifiedBy)
						VALUES (@CountryAbbreviation,@CountryName,@FIPSCode,SYSDATETIME(),@ModifiedBy)
					
					set @NewCountryID =@@IDENTITY;
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60031 Insert Failed Rollback';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertCounty]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUCounty
Description: Inserts data to LUCounty. 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertCounty](
	@CountyName NVarchar(20),
	@StateID int,
	@CityID int = 0,--Default cityID to 0 just in case it comes in later. 
	@ModifiedBy Name,
	@NewCountyID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCountyID int
	
	SET @TempCountyID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
		
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			IF @StateID = 0 --Must have a state before we can have a county!
				BEGIN
					SELECT @ErrorStatus = '-60065 StateID cant be NULL or 0';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
	
/****************************************************************************/

				SELECT @TempCountyID = CountyID 
				  FROM person.LUCounty
					 WHERE CountyName = Rtrim(Ltrim(@CountyName)) and StateID = @StateID
	     				If @TempCountyID <>0 
							BEGIN
								SET @ErrorStatus = ' -60062 County exists in LUCounty'; 
									RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
							END	

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

				IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60060';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
				 
			  INSERT Person.LUCounty(StateID,CityID,CountyName, ModifiedDate,ModifiedBy)
					VALUES (@StateID,@CityID,@CountyName,SYSDATETIME(),@ModifiedBy)
				
				set @NewCountyID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60061 Insert Failed LUCounty ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertDemographics]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



















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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Demographics
Description: Inserts data to Demographics table
Revisions:1 Nov 10. Added housing status to demographics table and altered stored procedures accordingly.
14 December 10. Added Country of Origin. GS
14 March 11. Added FamilyStatusType and Insurance Type GS
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertDemographics](
	@PersonID int,
	@EducationCategoryID int,
	@HousingStatus NVarchar(50)=NULL,
	@NumberInHousehold int,
	@Gender NVarchar(2) ='',
	@Race Nvarchar(20) = NULL,
	@CountryOfOrigin NVarchar(70) =NULL,--This could have used an ID, but keeping it simple since end users will be doing own crystal reports.
	@Ethnicity Nvarchar(20) = Null,
	@Disability NoYesMaybe =0,
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe=0 ,
	@FamilyStatusType Nvarchar(50),
	@InsuranceType Nvarchar(50),
	@FoodStamps NoYesMaybe =0,
	@HomeboundDelivery NoYesMaybe =0,
	@ModifiedBy Name,
	@NewDemographicsID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempDemographicsID int,
	@TempPersonId int
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempDemographicsID =0;		

	
		
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				SELECT @TempDemographicsID = DemographicsID 
				  FROM person.Demographics
					 WHERE PersonID = @PersonID
					 
				IF @TEMPDemographicsID <> 0 --If not zero then already exists. 
				   BEGIN
					SELECT @ErrorStatus = '-2005 DemogID already exists for PersonID';
					SET @ErrorStatus =0;
					RAISERROR(@ErrorStatus,16,1);
				   END        

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(20),@@ERROR) + ' -1000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				  INSERT Person.Demographics(PersonID,
											EducationCategoryID,
											HousingStatus,
											NumberInHousehold,
											Gender,
											Race,
											CountryOfOrigin,
											Ethnicity, 
											Disability,
											CSFP,
											Veteran, 
											HealthInsurance, 
											FamilyStatusType,
											InsuranceType,
											FoodStamps,
											HomeboundDelivery, 
											ModifiedDate, 
											ModifiedBy)
						VALUES				(@PersonID,
											@EducationCategoryID,
											@HousingStatus,
											@NumberInHousehold,
											@Gender, 
											@Race,
											@CountryOfOrigin,
											@Ethnicity,
											@Disability,
											@CSFP,
											@Veteran,
											@HealthInsurance,
											@FamilyStatusType,
											@InsuranceType,
											@FoodStamps,
											@HomeboundDelivery,SYSDATETIME(),@ModifiedBy)
					
					set @NewDemographicsID =@@IDENTITY;
					set @success =1;
					set @ErrorStatus ='';
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = Convert (Nvarchar(20),@@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-2001 Insert Fail Demographics';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END
END



















GO
/****** Object:  StoredProcedure [dbo].[pInsertEducationCategory]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUEducationCategory
Description: Inserts data to LUEducationCategory. 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertEducationCategory](
	@EducationLevel NVarchar(50),
	@ModifiedBy Name,
	@NewEducationCategoryID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempEducationCategoryID int
	
	SET @TempEducationCategoryID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
/****************************************************************************/

	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  
				SELECT @TempEducationCategoryID = EducationCategoryID 
				  FROM person.LUEducationCategory
					 WHERE EducationLevel = Rtrim(Ltrim(@EducationLevel))
	     				If @TempEducationCategoryID <>0 
							BEGIN
								SET @ErrorStatus = ' -60072 Education Catgory aready exists in LUEducationCategory'; 
									RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
							END	

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

					IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60070';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16,1);
					END
			  INSERT Person.LUEducationCategory(EducationLevel, ModifiedDate,ModifiedBy)
					VALUES (@EducationLevel,SYSDATETIME(),@ModifiedBy)
				
				set @NewEducationCategoryID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60071 Insert Failed Education Category';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertEthnicity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUEthnicity
Description: Inserts data to LUEthnicity. 
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertEthnicity](
	@EthnicityAbbreviation NVarchar(10),
	@EthnicityDescription NVarchar(50),
	@ModifiedBy Name,
	@NewEthnicityID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempEthnicityID int
	
	SET @TempEthnicityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
/****************************************************************************/

	
		
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
				SELECT @TempEthnicityID = EthnicityID 
				  FROM person.LUEthnicity
					 WHERE EthnicityAbbreviation = Rtrim(Ltrim(@EthnicityAbbreviation)) --Be a bit paranoid and trim the input for white spaces
				If @TempEthnicityID <>0 
					BEGIN
						SET @ErrorStatus = ' -60082 Ethnicity already exists'; --Failed in lookup table
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
						
					END	

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

				IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60080';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
				 
			  INSERT Person.LUEthnicity(EthnicityAbbreviation,EthnicityDescription, ModifiedDate,ModifiedBy)
					VALUES (@EthnicityAbbreviation,@EthnicityDescription,SYSDATETIME(),@ModifiedBy)
				
				set @NewEthnicityID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			    --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60081 Insert Failed Ethnicity';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertFamilyRelationship]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: FamilyRelationships
Description: Inserts data to FamilyRelationships. Do not confuse with the sp that inserts to the
family relationship LU table! This stored procedure is not called directly and its superior sps do the validation, so it is left out
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertFamilyRelationship](
	@PersonID int, 
	@ClientPersonID int ,
	@RelationshipID int,
	@RelationshipDescription nVarchar(50)='',
	@ModifiedBy Name, 
	@NewFamilyRelationshipID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempFamilyRelationshipID int
	
	SET @TempFamilyRelationshipID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/
--This stored procedure is not called directly and its superior sps do the validation, so it is left out
	
	BEGIN TRY
	  BEGIN TRANSACTION;
		
 
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-60040';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
		
	
			BEGIN
		
			  INSERT Person.FamilyRelationships(PersonId,ClientPersonID,RelationshipID,RelationDescription,ModifiedDate,ModifiedBy)
					VALUES (@PersonID,@ClientPersonID,@RelationshipID,@RelationshipDescription,SYSDATETIME(),@ModifiedBy)
				
				set @NewFamilyRelationshipID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
			END
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus  +'-18001 Insert Failed on FamilyRelationships';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [dbo].[pInsertFamilyStatusType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 14 March 11
*Table Name: LUFamilyStatusType
Description: Inserts data to pInsertFamilyStatusType
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertFamilyStatusType](
	@FamilyStatusType Nvarchar(50) ,
	@ModifiedBy Name,
	@NewFamilyStatusTypeID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempNewFamilyStatusTypeID int
	
	SET @TempNewFamilyStatusTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

			
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			SELECT @NewFamilyStatusTypeID = FamilyStatusTypeID 
			  FROM person.LUFamilyStatusType
			     WHERE FamilyStatusType = Rtrim(Ltrim(@FamilyStatusType)) 
	     			If @TempNewFamilyStatusTypeID <>0 
				    	BEGIN
					     	SET @ErrorStatus = ' -60022 Insurance Type already exists in LUFamilyStatusType'; 
							RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
						END	
			 
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  INSERT Person.LUFamilyStatusType(FamilyStatusType,ModifiedDate,ModifiedBy)
					VALUES (@FamilyStatusType,SYSDATETIME(),@ModifiedBy)
				
				set @NewFamilyStatusTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60021 Insert Failed on LUFamilyStatusType';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertFoodshelfCertification]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery6.sql|0|0|C:\Users\gSavard.WIN-QGO8QRSVG73\AppData\Local\Temp\3\~vs5A24.sql












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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Foodshelf.Certification, Foodshelf.Signature
Description: Inserts Food Shelf Certifications
Revisions: 28 March 11. Added CertificationTextID as a parameter
1 April 2011 Added Paper Certification Logic
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertFoodshelfCertification](
	@PersonID int,
	@CertificationDate DateTime,
	@Signature NVarchar(MAX),
	@ModifiedBy Name,
	@CertificationTextID int =0,--Default to this because paper certification does not have an id
	@IsPaperCertification bit,
	@PaperCertificationDate DateTime,
	@NewFoodShelfCertificationID int Output,
	@NewSignatureID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonId int
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
			
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
										 
					--IF @TempPersonID = 0 OR @TempPersonID IS NULL--Person Does Not Exist, Bail!
					--   BEGIN
					--	SET @Success = 0;
					--	SET @ErrorStatus ='-16005 PersonID cant be null/0';
					--	RAISERROR(@ErrorStatus,16,1);
					--   END        
				
				SELECT @TempPersonID = PersonID 
				  FROM person.Person
					 WHERE PersonID = @PersonID
					 
				IF @TempPersonID = 0 OR @TempPersonID IS NULL
					BEGIN
						SET @Success =0;
						SET @ErrorStatus ='-16008 PersonID does not exist in Person';
						RAISERROR (@ErrorStatus,16,1);
					END
					
				--IF @CertificationTextID =0 OR @CertificationTExtID IS NULL
					--BEGIN
					--	SET @Success =0;
					--	SET @ErrorStatus ='CertificationTextID is mandatory';
					--	RAISERROR (@ErrorStatus, 16, 1)
					--END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -16000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END
/*IF this is a paper certification then we will have a CertificationTextID of 0*/
				  INSERT Foodshelf.FoodShelfCertification (PersonID,CertificationTextID,LastCertificationDate,IsPaperCertification,PaperCertificationDate,ModifiedDate,ModifiedBy)
					VALUES (@PersonID,@CertificationTextID,@CertificationDate,@IsPaperCertification,@PaperCertificationDate,SYSDATETIME(),@ModifiedBy);
					
					IF @@Error <> 0 
						BEGIN
							SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -16001 insert Failed FoodShelfCertification';
							SET @Success = 0;
							RAISERROR(@ErrorStatus, 16, 1);
						END
					
					set @NewFoodshelfCertificationID =@@IDENTITY;
					set @success =1;
					set @ErrorStatus ='';
			--We only call Foodshelf.Signature if this is an electronic certification
			If @IsPaperCertification =0
				Begin	
				 INSERT Foodshelf.Signature (PersonID,FoodShelfCertificationID,Signature,ModifiedDate, ModifiedBy) 
					VALUES (@PersonID,@NewFoodshelfCertificationID,@Signature,SYSDATETIME(),@ModifiedBy);
				END	
					
					IF @@Error <> 0 
						BEGIN
							SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -16001 insert Failed Signature';
							SET @Success = 0;
							RAISERROR(@ErrorStatus, 16, 1);
						END	
					SET @NewSignatureID = @@IDENTITY;
					SET @Success =1;
					SET @ErrorStatus ='';
					
				
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-16001 Insert Fail Certification ';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END
END












GO
/****** Object:  StoredProcedure [dbo].[pInsertFoodTypeGiven]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: FoodTypeGiven
Description: Inserts data to FoodTypeGiven. This SP requires PersonID, to be valid on input
in order to capture the appropriate information. ReceivedDate should also be a valid date/time since we need to be able
to return up to 90 days history for each client in reports. This date is not tested since we have to assume
that the record may have been input on paper for some reason, so we cannot use system date to test validity.
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertFoodTypeGiven](
	@PersonID int ,
	@ReceivedDate DateTime,
	@FoodGiven FoodShelf.GroceryOrBreadProduce,
	@ModifiedBy Name,
	@NewFoodTypeGivenID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int

	SET @TempPersonID =0;
			
	SET @Success = 0;
	SET @ErrorStatus ='';
/****************************************************************************/

	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  --Make sure that we do not have bad data
		  IF (@PersonID = 0) OR (@PersonID IS NULL) 
			BEGIN
				SELECT @ErrorStatus = ' -600011 PersonID/ not valid';
				SET @Success = 0;
				RAISERROR(@ErrorStatus,16,1);
			END
		  
		  --We now have a valid range for each ID, but need to be sure that they exist in the database before trying the insert. We check the PersonProgramServicesUsed
		  --table since that ties the three IDs together. We have to assume that the record has already been insert to this table since this
		  --is a child of that table
			SELECT @TempPersonID = PersonID 
			  FROM person.Person
			     WHERE  PersonID=@PersonID   
	     			
	     			IF (@TempPersonID =0) OR (@TempPersonID IS NULL) 
				    	BEGIN
					     	SET @ErrorStatus = ' -600014 Person record does not exist in Person'; 
							RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
						END	
			 
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-600010';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  INSERT Foodshelf.FoodTypeGiven(PersonID,ReceivedDate,FoodGiven,ModifiedDate,ModifiedBy)
					VALUES (@PersonID,@ReceivedDate,@FoodGiven,SYSDATETIME(),@ModifiedBy)
				
				set @NewFoodTypeGivenID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-600011 Insert Failed on FoodTypeGiven';
			  RAISERROR(@ErrorStatus, 16, 1);
		
		END CATCH
	END
END


GO
/****** Object:  StoredProcedure [dbo].[pInsertHouseholdNotes]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO














/*************************************************************************************************
*Author: Gary Savard
*Date: 2 NOV 10
*Table Name: FoodShelf.Household Notes
Description: Inserts data to FoodShelf.HouseHoldNotes table.This table is for the notes associated with the
food shelf intake screens. There are 3 ID fields, the HouseholdNotesID is the identity. ClientPersonID
is the PersonID of the individual on which the note was written. The HouseholdMemberPersonID is optional, and
If this person is not the client, but a household member, this value will be the Client's personID. We 
may not need this field, but it is added for potential future functionality
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertHouseholdNotes](
	@ClientPersonID int,
	@HouseholdMemberPersonID int,
	@Notes Nvarchar(MAX),
	@ModifiedBy Name,
	@NewHouseholdNotesID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempHouseholdNotesID int,
	@TempClientPersonID int,
	@TempHouseholdMemberPersonID int
	
	SET @TempHouseholdNotesID =0;
	SET @TempClientPersonID = 0;	
	SET @Success = 0;
	SET @ErrorStatus ='';
	



		BEGIN TRY
		  BEGIN TRANSACTION;
				/****************************************************************************/
			--Validate both IDs coming in. Only the ClientPersonID is mandatory, so we check the HouseholdMemberPersonID only if it is not
			--0 or NULL
			SELECT @TempClientPersonID = PersonID 
			  FROM person.Person
				 WHERE PersonID = @ClientPersonID
			
			If @TempClientPersonID = 0 or @TempClientPersonID IS NULL
			BEGIN
				SET @ErrorStatus = ' -14032 ClientPersonID does not exist in Person'; --Failed in person table
				SET @Success =0;
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
				
			END	
		
		--Since this is an optional field, we only check it if it has a value other than 0 or NULL	
		IF @HouseholdMemberPersonID <> 0 AND @HouseholdMemberPersonID IS NOT NULL	
		 BEGIN
			SELECT @TempHouseholdMemberPersonID = @HouseholdMemberPersonID
				FROM Person.Person
					WHERE PersonID = @HouseholdMemberPersonID
		
			IF @TempHouseholdMemberPersonID = 0 OR @TempHouseholdMemberPersonID IS NULL
				BEGIN
					SET @ErrorStatus =' -14016 HouseholdMemberPersonID does not exist, though not NULL/0';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END
		 END			
				
		/****************************************************************************/	          

			
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-14000';
				SET @Success = 0;
				RAISERROR (@ErrorStatus,16,1);
			END
			
			  INSERT Foodshelf.HouseholdNotes (ClientPersonID, HouseholdMemberPersonID, Notes,ModifiedBy, ModifiedDate)
					Values(@ClientPersonID,@HouseholdMemberPersonID,@Notes,@ModifiedBy,SYSDATETIME());
				
				SET @NewHouseholdNotesID =@@IDENTITY;
				SET @success =1;
				SET @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			 --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			 
			 SELECT @ErrorStatus =@ErrorStatus + ' -14001' +' Insert Failed HouseholdNotes';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END














GO
/****** Object:  StoredProcedure [dbo].[pInsertHouseholdTransferOptions]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



/*************************************************************************************************
*Author: Gary Savard
*Date: 22 April 11
*Table Name: LUInsertHouseholdTransferOptions
Description: Inserts data to LUInsertHouseholdTransferOptions. This is a free format input so there is
a strong possibility that we will have duplicates, but those should be easily eliminated by the maintenance screens.
Revisions:

**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertHouseholdTransferOptions](
	@ActionToTake Nvarchar(50),
	@ActionToTakeDescription NVarchar(MAX),
	@ModifiedBy Name,
	@NewActionToTakeID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

BEGIN
	DECLARE
	@TempActionToTakeID int
	
	SET @TempActionToTakeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		
	

		BEGIN TRY
			BEGIN TRANSACTION;
		
			/****************************************************************************/
				--Avoid Duplicate Rows! However, a typo on input such as 'Hmoe' instead of 'Home' will do an isert.
				--Can't avoid finger problems!
				
			SELECT @TempActionToTakeID = HouseholdTransferActionID 
			  FROM dbo.LUHouseholdTransferOptions
				 WHERE ActionToTake = Rtrim(Ltrim(@ActionToTake)) --Be a bit paranoid and trim the input for white spaces
			If @TempActionToTakeID <> 0 --Already Exists
				BEGIN
					SELECT @ErrorStatus = '-7015 Action Already Exists';
					SET @Success =0;
					RAISERROR(@ErrorStatus, 16, 1);
				END

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

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = Convert (nVarchar(50),@@ERROR) + ' -6010';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16, 1);
	END
	 
			
			  INSERT dbo.LUHouseholdTransferOptions(ActionToTake,ActionToTakeDescription,ModifiedDate, ModifiedBy)
					VALUES (@ActionToTake,@ActionToTakeDescription,SYSDATETIME(),@ModifiedBy)
				
				set @NewActionToTakeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus ='';
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
		
			  SET @Success =0;
			  SELECT  @ErrorStatus = @ErrorStatus + 'Rollback -6011';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		

END








GO
/****** Object:  StoredProcedure [dbo].[pInsertHousingStatus]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUHousingStatus
Description: Inserts data to LUHousingStatus. 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertHousingStatus](
	@HousingStatus NVarchar(20),
	@ModifiedBy Name,
	@NewHousingStatusID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempHousingStatusID int
	
	SET @TempHousingStatusID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

	 
	BEGIN TRY
		BEGIN TRANSACTION;
			/****************************************************************************/

			SELECT @NewHousingStatusID = HousingStatusID 
			  FROM person.LUHousingStatus
				 WHERE HousingStatus = Rtrim(Ltrim(@HousingStatus)) --Be a bit paranoid and trim the input for white spaces
			If @TempHousingStatusID <>0 
				BEGIN
					SET @ErrorStatus = ' -60092 already exists LUHousingStatus'; --Failed in lookup table
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
					
				END	

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

				IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
			
				BEGIN
		
		 			INSERT Person.LUHousingStatus(HousingStatus, ModifiedDate,ModifiedBy)
						VALUES (@HousingStatus,SYSDATETIME(),@ModifiedBy)
				
					set @NewHousingStatusID =@@IDENTITY;
					set @success =1;
					set @ErrorStatus =0;
					COMMIT TRANSACTION;
				END
		
	
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + +'-60021 Insert Failed Housing Status';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
END








GO
/****** Object:  StoredProcedure [dbo].[pInsertIncomeSource]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Address
Description: Inserts data to LUIncomeSource table.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertIncomeSource](
	@IncomeSourceAbbreviation NVarchar(10),
	@IncomeSourceDescription Nvarchar(50),
	@ModifiedBy Name,
	@NewIncomeSourceID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempIncomeSourceID int
	
	SET @TempIncomeSourceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		

/****************************************************************************/
	
		
	BEGIN TRY
	  BEGIN TRANSACTION;
			--the address, so we need to be sure that the data matches an address type before continuing.
		SELECT @TempIncomeSourceID = IncomeSourceID 
		  FROM person.LUIncomeSource
			 WHERE IncomeSourceAbbreviation = Rtrim(Ltrim(@IncomeSourceAbbreviation)) --Be a bit paranoid and trim the input for white spaces
				
				If @TempIncomeSourceID <> 0
				BEGIN
					SET @ErrorStatus = ' -6092 Income Source exists in LUIncomeSource'; --Failed in lookup table
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
					
				END	
/****************************************************************************/	          

					IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = @@ERROR + '-6090';
						SET @Success = 0;
						RAISERROR (@ErrorStatus,16,1);
					END
	 
		
		
			  INSERT Person.LUIncomeSource(IncomeSourceAbbreviation,IncomeSourceDescription,ModifiedDate, ModifiedBy)
					VALUES (@IncomeSourceAbbreviation, @IncomeSourceDescription, SYSDATETIME(),@ModifiedBy)
				
				set @NewIncomeSourceID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
				--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			 SELECT @ErrorStatus =@ErrorStatus + ' -6091' +' Insert Failed LUIncomeSource';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertInsuranceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 14 March 11
*Table Name: LUInsuranceType
Description: Inserts data to pInsertInsuranceType
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertInsuranceType](
	@InsuranceType Nvarchar(50) ,
	@ModifiedBy Name,
	@NewInsuranceTypeID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempNewInsuranceTypeID int
	
	SET @TempNewInsuranceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

			
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			SELECT @NewInsuranceTypeID = InsuranceTypeID 
			  FROM person.LUInsuranceType
			     WHERE InsuranceType = Rtrim(Ltrim(@InsuranceType)) 
	     			If @TempNewInsuranceTypeID <>0 
				    	BEGIN
					     	SET @ErrorStatus = ' -60022 Insurance Type already exists in LUInsuranceType'; 
							RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
						END	
			 
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  INSERT Person.LUInsuranceType(InsuranceType,ModifiedDate,ModifiedBy)
					VALUES (@InsuranceType,SYSDATETIME(),@ModifiedBy)
				
				set @NewInsuranceTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60021 Insert Failed on LUInsuranceType';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END










GO
/****** Object:  StoredProcedure [dbo].[pInsertJournalClientFamilyChanges]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO











/*************************************************************************************************
*Author: Gary Savard
*Date: 25 April 2011
*Table Name: JournalClientFamilyChanges
Description: Inserts data to journal requested changes to a family  member's household. A volunteer doing intake
may find that a household member potentially exists under a different client. The volunteer checks an appropriate box
for investigation, changes. The request is stored here along with the previous and new client's ID, if appropriate since
there may be reason to delete one of the persons involved.

13 July 11 - Temporarily removed check for @PreviousClientID
**************************************************************************************************/



CREATE PROCEDURE [dbo].[pInsertJournalClientFamilyChanges](
	@HouseholdMembersID int , 
	@PreviousClientsID int ,
	@NewClientsID int,
	@ActionTaken nVarchar(50),
	@Notes       nVarchar(MAX),
	@ModifiedBy Name, 
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

BEGIN
	
			
--	SET @Success =0;
--	SET @ErrorStatus ='';
	
	
/****************************************************************************/

	BEGIN TRY
	  BEGIN TRANSACTION;
		
 
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-60040';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
			
			--Checking for some things that have to have a value
			IF @HouseholdMembersID =0 OR @HouseholdMembersID IS NULL
				BEGIN
					SELECT @ErrorStatus ='Household Member ID cannot be null or 0';
					SET @Success =0;
					RAISERROR (@Errorstatus,16,1);
				END
			--Do them individually instead of one big IF statement for clarity	
			--IF @PreviousClientsID = 0 or @PreviousClientsID IS NULL
			--	BEGIN
			--		SELECT @ErrorStatus ='PreviousClientsID cannot be null or 0';
			--		SET @Success =0;
			--		RAISERROR(@ErrorSTatus,16,1);
			--	END
-- This could be a delete request so we do not care if @NewClientsID is null or 0
--			

--Must have an action
			IF @ActionTaken IS NULL or @ActionTaken =''
				BEGIN
					SELECT @ErrorStatus ='Action taken must have a value';
					SET @Success =0;
					RAISERROR(@ErrorSTatus,16,1);
				END
				
				
			BEGIN
		
			  --Add the entry
					INSERT dbo.JournalClientFamilyChanges
								(
									HouseholdMembersID,
									PreviousClientsID,
									NewClientsID,
									ActionTaken,
									Notes,
									ModifiedBy,
									ModifiedDate
								)
						VALUES
								(
									@HouseholdMembersID,
									@PreviousClientsID,
									@NewClientsID,
									@ActionTaken,
									@Notes,
									@ModifiedBy,
									SYSDATETIME()
													
								)
								
				
				SET @success =1;
				SET @ErrorStatus ='';
				COMMIT TRANSACTION;
			END
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus  +'-18001 Insert Failed on JournalClientFamilyChanges';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
















GO
/****** Object:  StoredProcedure [dbo].[pInsertJournalLookupTableChanges]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO












/*************************************************************************************************
*Author: Gary Savard
*Date: 25 April 2011
*Table Name: JournalLookupTableChanges
Description: Inserts data to journal requested changes to Lookup tables.. 
**************************************************************************************************/


CREATE PROCEDURE [dbo].[pInsertJournalLookupTableChanges](
	@LUChangeTable LUTableChanges READONLY,
	@ModifiedBy Name

	)
AS
SET NOCOUNT ON;

BEGIN
DECLARE
@ROWCOUNT int,
@LoopCount int

SET @ROWCOUNT=0;
SET @LoopCount =1;
			
	
	
/****************************************************************************/

	BEGIN TRY
	  BEGIN TRANSACTION;
		--How many records do we process
 		SELECT @ROWCOUNT = (SELECT COUNT(*) FROM @LUChangeTable)
				
			BEGIN
			
						--WHILE  @LoopCount<=@RowCount
						--	BEGIN
							
									
					--Add the entry
					INSERT INTO dbo.JournalLookupTableChanges
								(
									TableName,
									ActionTaken,
									OldValue,
									OldLUTableID,
									NewValue,
									ModifiedBy,
									ModifiedDate
								)
					SELECT t.TableName, t.ActionTaken, t.OldValue,t.OldLUTableID, t.NewValue,@ModifiedBy,SYSDATETIME() from @LUChangeTable as t
						--VALUES
						--		(
						--		    @TableName,
						--			@ActionTaken,
						--			@OldValue,
						--			@OldLUTableID,
						--			@NewValue,
						--			@ModifiedBy,
						--			SYSDATETIME()
						--		)
					--	SET @LoopCount =@LoopCount +1
					--END--End While @Rowcount
								
					
				
				COMMIT TRANSACTION;
			END
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			--Not doing error handling in this sp. Not needed other than rollback		
			
			
		END CATCH
		
	END

















GO
/****** Object:  StoredProcedure [dbo].[pInsertLanguage]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO









/*************************************************************************************************
*Author: Gary Savard
*Date: 15 Oct 10
*Table Name: LULanguage
Description: Inserts data to LULangage. This table Contains the most common languages and dialects in the world.Dialects
are comma demlmited. Example: Chinese, Mandarin.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertLanguage](
	@LanguageName Nvarchar(50),
	@ModifiedBy Name,
	@NewLanguageID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempLanguageID int
	
	SET @TempLanguageID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		BEGIN TRY
		  BEGIN TRANSACTION;
		  /****************************************************************************/
			--Since some languages are comma delimited by dialect, we will use Soundex to test if the language already exists
			--in the db
			SELECT @TempLanguageID = LanguageID 
			  FROM person.LULanguage
				 WHERE LanguageName = Soundex(Rtrim(Ltrim(@LanguageName))) --Be a bit paranoid and trim the input for white spaces


			/****************************************************************************/	          
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '  -6060';
					SET @Success = 0;
					RAISERROR(@ErrorStatus,16,1);
				END
			 
				
				IF @TempLanguageID = 0 --If they don't exist in the database then
					BEGIN
					
						INSERT Person.LULanguage (LanguageName,ModifiedDate, ModifiedBy)
									VALUES (@LanguageName,SYSDATETIME(),@ModifiedBy)
								
								set @NewLanguageID =@@IDENTITY;
								set @success =1;
								set @ErrorStatus =0;
						COMMIT TRANSACTION;
					END		
				
			END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT  @ErrorStatus= @ErrorStatus + 'LULanguage-6061';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pInsertLanguagesSpoken]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
*Author: Gary Savard
*Date: 15 Oct 10
*Table Name: LanguagesSpoken
Description: Inserts data to LanguagesSpoken. An individual may speak more than one language so this is assumed to
be one to many. We need to check to ensure the languageID exists in the language lookup table.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertLanguagesSpoken](
	@LanguageID int,
	@PersonID int,
	@IsPrimaryLanguage bit,
	@ModifiedBy Name,
	@NewLanguagesSpokenID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempLanguageID int,
	@TempPersonID int,
	@TempLanguagesSpokenID int
	
	SET @TempLanguageID =0;
	SET @TempPersonId =0;
	SET @TempLanguagesSpokenID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		BEGIN TRY
		  BEGIN TRANSACTION;
		  /****************************************************************************/
			IF ((@PersonID = 0) OR (@PersonID IS NULL)) OR ((@LanguageID =0) OR (@LanguageID IS NULL))
				BEGIN	
					SELECT @ErrorStatus = '-11005 PersonID/LanguageID cant be 0/NULL';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1); 
				END
			
			SELECT @TempLanguageID = LanguageID 
			  FROM person.LULanguage
				 WHERE LanguageID = @LanguageID
			
			SELECT @TempPersonID = PersonID
				FROM Person.Person
					Where PersonID = @PersonID
					
			IF @TempLanguageID = 0 OR @TempLanguageID IS NULL
				BEGIN
					SELECT @ErrorStatus ='-11008 LanguageID does not exist in LULanguage';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END		
			IF @TempPersonID = 0 OR @TempPersonID IS NULL
				BEGIN
					SELECT @ErrorStatus ='-11008 PersonID does not exist in Person';
					SET @Success=0;
					RAISERROR(@ErrorStatus,16,1);
				END	

			--Final check to be sure this is not a duplicate
			
			SELECT @TempLanguagesSpokenID = LanguagesSpokenID 
				FROM Person.LanguagesSpoken
					WHERE LanguageID = @LanguageID AND PersonID =@PersonID
			
			IF @TempLanguagesSpokenID <> 0 
				--This already exists! Duplicate Row Error
				BEGIN
					SELECT @ErrorStatus = '-11009 Duplicate Row Exists';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END
				


			/****************************************************************************/	          
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '  -6060';
					SET @Success = 0;
					RAISERROR(@ErrorStatus,16,1);
				END
			 
				
				--If they don't exist in the database then
				
					
						INSERT Person.LanguagesSpoken(LanguageID,PersonID,IsPrimaryLanguage,ModifiedDate, ModifiedBy)
									VALUES (@LanguageID,@PersonID,@IsPrimaryLanguage,SYSDATETIME(),@ModifiedBy)
								
								set @NewLanguagesSpokenID =@@IDENTITY;
								set @success =1;
								set @ErrorStatus =0;
						COMMIT TRANSACTION;
						
				
			END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT  @ErrorStatus= @ErrorStatus + 'Languages Spoken -11001';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pInsertLUfamilyRelationships]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUFamilyRelationships
Description: Inserts data to LUFamilyRelationships.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertLUfamilyRelationships](
	@RelationshipCode Nvarchar(30),
	@RelationshipDescription Nvarchar(50) ='',
	@ModifiedBy Name,
	@NewFamilyRelationshipID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempFamilyRelationshipID int
	
	SET @TempFamilyRelationshipID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

	
	BEGIN TRY
	  BEGIN TRANSACTION;
		 SELECT @TempFamilyRelationshipID = FamilyRelationshipID 
			  FROM person.LUFamilyRelationship
				WHERE RelationshipCode = Rtrim(Ltrim(@RelationshipCode)) 
	     IF @TempFamilyRelationshipID <>0 
				BEGIN
					SET @ErrorStatus = ' -60042 Relationship exists in LUFamilyRelationship'; 
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
					
				END	
 
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-60040';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
		
	IF @TempFamilyRelationshipID = 0 -- Don't really need this with the above raise error, but for clarity.If they don't exist in the database then
		BEGIN
		
			  INSERT Person.LUFamilyRelationship(RelationshipCode,RelationshipDescription,ModifiedDate,ModifiedBy)
					VALUES (@RelationshipCode,@RelationshipDescription,SYSDATETIME(),@ModifiedBy)
				
				set @NewFamilyRelationshipID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
			END
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus  +'-60041 Insert Failed on LUFamilyRelationship';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pInsertPerson]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







/*************************************************************************************************
*Lookup Table Stored Procedure Template. Change XXX in name to the name of the table that will get the insert. This is to be used
*for single table inserts only. 
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Person
Description: Iserts data to Person table
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertPerson](
	@Title NVarchar(8) =NULL,
	@FirstName Name,
	@MiddleName Name = Null,
	@LastName Name,
	@Suffix NVarchar(10) = Null,
	@DateOfBirth DateTime,
	@EmailAddress Nvarchar(50) = Null,
	@EmailContactPreference NoYes =0,
	@ModifiedBy Name,
	@NewPersonID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int,
	@PersonID int;
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempPersonID =0;		

	
	           
BEGIN TRY
	 BEGIN TRANSACTION;
	
	 SELECT @TempPersonID = PersonID 
	  FROM person.Person
	     WHERE Firstname = @FirstName AND LastName = @LastName AND
	           DateOfBirth =@DateOfBirth
		IF @TempPersonID <>0
			BEGIN
				SELECT @ErrorStatus =  'Person Already Exists -1017';
				SET @Success = 0;
				RAISERROR(@ErrorStatus,16,1);
			END
		
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-1000';
				SET @Success = 0;
				RAISERROR(@ErrorStatus,16,1);
			END
		 
			
			  INSERT Person.Person(Title,FirstName,MiddleName,LastName, Suffix,DateOfBirth, EmailAddress, EmailContactPreference, ModifiedDate, ModifiedBy, IsDeleted)
					VALUES (@Title, @FirstName, @MiddleName,@LastName,@Suffix,@DateOfBirth,@EmailAddress,@EmailContactPreference,SYSDATETIME(),@ModifiedBy, 0)
				
				set @NewPersonID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
	
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SET @ErrorStatus=  @ErrorStatus + '-1001';
			  RAISERROR(@ErrorStatus, 15, 1);
		
			  
		END CATCH
		
	END








GO
/****** Object:  StoredProcedure [dbo].[pInsertPersonType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUPersonType
Description: Inserts data to LUPersonType. 
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertPersonType](
	@PersonType NVarchar(20),
	@ModifiedBy Name,
	@NewPersonTypeID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonTypeID int
	
	SET @TempPersonTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

BEGIN TRY
	BEGIN TRANSACTION;
	/****************************************************************************/
	--Does it already exist? If so, don't insert it.
	SELECT @TempPersonTypeID = PersonTypeID  
	  FROM person.LUPersonType
	     WHERE PersonType = Rtrim(Ltrim(@PersonType)) 

/****************************************************************************/	          
		IF @TempPersonTypeID <> 0
			BEGIN
				SELECT @ErrorStatus = @@ERROR + '-600007 PersonType already exists';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = @@ERROR + '-600000';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
		 
		
	
		BEGIN
		
			  INSERT Person.LUPersonType(PersonType,ModifiedDate,ModifiedBy)
					VALUES (@PersonType,SYSDATETIME(),@ModifiedBy)
				
				set @NewPersonTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		END
END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600001 Insert Failed Person Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pInsertPhone]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Phone
Description: Inserts data to phone table. The row is tied to the person.personid. This Stored proc/table does not directly
access the LUPhoneType table. The type is selected by the user from a dropdown and we just store the ID from the dropdown behind the scenes  
 for simplicity
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertPhone](
	@PersonID int,
	@PhoneNumber Phone,
	@PhoneExtension NVarchar(8),
	@PhoneType int,
	@ModifiedBy Name,
	@PhoneID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPhoneID int,
	@TempPersonID int
	
	SET @TempPhoneID =0;
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
    BEGIN TRY
		  BEGIN TRANSACTION;
			IF @PersonID = 0 OR @PersonID IS NULL -- This has to be valid or we bail out!
				BEGIN
					SET @Success =0;
					SET @ErrorStatus = '8008: PersonID must be valid';
						
					RAISERROR(@ErrorStatus,16,1);
				END
				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = @@ERROR + '-8030';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

	 	
			  INSERT Person.Phone(PersonID,PhoneNumber,PhoneExtension, PhoneType,ModifiedDate, ModifiedBy)
					VALUES (@PersonID,@PhoneNumber,@PhoneExtension, @PhoneType,SYSDATETIME(),@ModifiedBy)
				
				set @PhoneID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
				
		  COMMIT TRANSACTION;
			
	END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
				
	  	    SELECT @ErrorStatus= @ErrorStatus + '8001';
		    RAISERROR(@ErrorStatus, 16, 1);
		    SET @Success =0;
			 
			
		END CATCH

		













GO
/****** Object:  StoredProcedure [dbo].[pInsertPhoneType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 12 Oct 10
*Table Name: LUPhoneType
Description: Inserts Phone Type to the LUPhoneType table.The data in this table could easily become
poor if the user does not take care when inserting phone types. A mis-spelling can cause unintential duplicate
records.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertPhoneType](
	@PhoneType int,
	@ModifiedBy Name,
	@NewPhoneTypeID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPhoneTypeID int
	
	SET @TempPhoneTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	


		 
BEGIN TRY
  BEGIN TRANSACTION;	
  /****************************************************************************/
	--Check to be sure that the Phone Type doesn't already exist.
	SELECT @TempPhoneTypeID = PhoneTypeID
	  FROM person.LUPhoneType
		 WHERE PhoneType = ltrim(rtrim(@PhoneType))	 
	
	IF @TempPhoneTypeID <> 0
	BEGIN
	SET @ErrorStatus = '-6082' + ' PhoneType exists in LUPhoneType' ; --Failed in lookup table
		RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
		
	END	
       

	IF @@Error <> 0 
		BEGIN
			SET @ErrorStatus = '-6080';
			SET @Success = 0;
			RAISERROR (@ErrorStatus,16,1);
		END
	   	
	  	  INSERT Person.LUPhoneType(PhoneType,ModifiedDate, ModifiedBy)
				VALUES (@PhoneType, SYSDATETIME(),@ModifiedBy)
				
			set @NewPhoneTypeID =@@IDENTITY;
			set @success =1;
			set @ErrorStatus ='';
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
		--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			 
			  SET @ErrorStatus= @Errorstatus + ' -6081' +'Insert Failed on Phone Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			  ROLLBACK TRANSACTION;
		END CATCH
		

END








GO
/****** Object:  StoredProcedure [dbo].[pInsertPostalCode]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








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

*Author: Gary Savard
*Date: 12 Oct 10
*Table Name: Address
Description: Inserts Postal Code to the Postal Code table.This requires that the CityID be passed in as a
paramter. It is unlikely that a new city will be build, requiring a new postal code, but it is very likely
that a new postal code will be needed in a city.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertPostalCode](
	@CityID int,
	@PostalCode Nvarchar(10),
	@ModifiedBy Name,
	@NewPostalCodeID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCityID int
	
	
	SET @TempCityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	


		
BEGIN TRY
	BEGIN TRANSACTION;	 
	/****************************************************************************/
	--Check to be sure that the city does exist in the city table before we go on.
	SELECT @TempCityID = CityID
	  FROM person.LUCity
		 WHERE CityID = @CityID
	
	IF @TempCityID = 0
		BEGIN
			SET @ErrorStatus = '-6072' + ' CityID doesnt exist LUCity, cant insert PostalCode' ; --Failed in lookup table
			RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
			
		END	
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SET @ErrorStatus = '-6070';
		SET @Success = 0;
		RAISERROR (@ErrorStatus,16,1);
	END
	 
		
		  INSERT Person.LUPostalCode(CityID,PostalCode,ModifiedDate, ModifiedBy)
					VALUES (@CityID, @PostalCode, SYSDATETIME(),@ModifiedBy)
				
				set @NewPostalCodeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus ='';
				COMMIT TRANSACTION;
		
END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SET @ErrorStatus='-6071' +'Insert Failed on PostalCode';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			  
		END CATCH
		

END








GO
/****** Object:  StoredProcedure [dbo].[pInsertPrograms]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Programs
Description: Inserts data to Programs table. This table creates the one to many relationship between a person and programs. Each person
may use 0 or more programs. If they are not using a program, we will not do an insert to this table.
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pInsertPrograms](
	@PersonID int,
	@ProgramID int,
	@ModifiedBy Name,
	@NewProgramsID int output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempProgramID int,
	@TempPersonID int
	
	SET @TempPersonID =0;
	SET @TempProgramID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
			
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
			IF (((@PersonID = 0)OR (@PersonID IS NULL)) OR ((@ProgramID =0) OR (@ProgramID IS NULL)))
				BEGIN
					SELECT @ErrorStatus =' -9005 PersonID/ProgramID Cant be 0/NULL';
					SET @Success =0;
					RAISERROR (@ErrorStatus,16,1);
				END
			
			
			--Are these valid ids? 
				SELECT @TempPersonID = PersonID 
				  FROM person.Person
					 WHERE PersonID = @PersonID
					 
				SELECT @TempProgramID = @ProgramID
				  FROM Person.LUProgramType
					  WHERE ProgramTypeID = @ProgramID
					 
				IF @TempPersonID = 0 OR @TempPersonID IS NULL--Cant have these! 
				   BEGIN
					SELECT @ErrorStatus = '-9005 PersonID doesnt exist';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				   END        
				   
				 IF @TempProgramID = 0 OR @TempProgramID IS NULL 
					BEGIN
						SELECT @ErrorStatus = '-9006 ProgramID doesnt exist';
						SET @Success =0;
						RAISERROR (@ErrorStatus,16,1);
					END  

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -1000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				  INSERT Person.Programs(PersonID,ProgramID,ModifiedDate, ModifiedBy)
						VALUES (@PersonID, @ProgramID, SYSDATETIME(),@ModifiedBy)
					
					SET @NewProgramsID = @@IDENTITY;
					SET @success =1;
					SET @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-9011 Insert Fail Programs';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END
END









GO
/****** Object:  StoredProcedure [dbo].[pInsertProgramServicesUsed]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: ProgramServicesUsed
Description: Inserts data to child of Services.The IDs (PersonID,ProgramID,ProgramServiceID) must all be correct to do an insert.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertProgramServicesUsed](
	@ProgramServiceID int,
	@PersonID int,
	@ProgramID int,
	@ModifiedBy Name,
	@NewProgramServiceUsedID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempProgramServiceID int,
	@TempPersonID int,
	@TempProgramID int
	
	SET @TempProgramServiceID =0;
	SET @TempPersonID =0;
	SET @TempProgramID=0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
         
BEGIN TRY
	  BEGIN TRANSACTION;
	  --All have to be valid
	  IF (@PersonID = 0 OR @PersonID IS NULL) OR (@ProgramID =0 OR @ProgramID IS NULL) OR (@ProgramServiceID = 0 OR @ProgramServiceID IS NULL)
		BEGIN
			SELECT @ErrorStatus ='-10005 PersonId,ProgramID,ProgramServiceID cant be 0/NULL';
			SET @Success =0;
			RAISERROR(@ErrorStatus,16,1);
		END	
			
	--Now check to see that each ID exists in the appropriate table
	
		SELECT @TempPersonID = PersonID
			FROM Person.Person
				WHERE PersonID = @PersonID
				
		SELECT @TempProgramID = ProgramTypeID
			FROM Person.LUProgramType
				WHERE ProgramTypeID = @ProgramID
				
		SELECT @TempProgramServiceID = ProgramServiceTypeID
			FROM Person.LUProgramServiceType
				WHERE ProgramServiceTypeID = @ProgramServiceID 
				
	 IF (@TempPersonID = 0 OR @TempPersonID IS NULL) OR (@TempProgramID =0 OR @TempProgramID IS NULL) OR (@TempProgramServiceID = 0 OR @TempProgramServiceID IS NULL)
		BEGIN
			SELECT @ErrorStatus ='-10008 PersonId,ProgramID or ProgramServiceID does not exist';
			SET @Success =0;
			RAISERROR(@ErrorStatus,16,1);
		END	
				
				
					
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6040';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
		 
		
	  BEGIN
			  INSERT Person.ProgramServicesUsed(PersonID,ProgramID,ProgramServiceID,ModifiedDate, ModifiedBy)
					VALUES (@PersonID,@ProgramID,@ProgramServiceID,SYSDATETIME(),@ModifiedBy)
				
				set @NewProgramServiceUsedID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			 COMMIT TRANSACTION;
		END
		
	END TRY

		BEGIN CATCH
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus=@@ERROR +@ErrorStatus+ '-10001';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pInsertProgramServiceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUProgramServiceType
Description: Inserts data to LUProgramServiceType. This table matches the Program with the service being
used by the client.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertProgramServiceType](
	@ServiceCode Nvarchar(20),
	@ServiceDescription NVarchar(50),
	@ModifiedBy Name,
	@NewProgramTypeID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempProgramServiceTypeID int
	
	SET @TempProgramServiceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
/****************************************************************************/
	
	SELECT @TempProgramServiceTypeID = ProgramServiceTypeID 
	  FROM person.LUProgramServiceType
	     WHERE ServiceCode = Rtrim(Ltrim(@ServiceCode)) --Be a bit paranoid and trim the input for white spaces
	 

/****************************************************************************/	          
BEGIN TRY
	  BEGIN TRANSACTION;
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6040';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
		 
		
	IF @TempProgramServiceTypeID = 0 --If they don't exist in the database then
	  BEGIN
		
			  INSERT Person.LUProgramServiceType(ServiceCode,ServiceDescription,ModifiedDate, ModifiedBy)
					VALUES (@ServiceCode,@ServiceDescription,SYSDATETIME(),@ModifiedBy)
				
				set @TempProgramServiceTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			 COMMIT TRANSACTION;
		END
		
	END TRY

		BEGIN CATCH
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus=@@ERROR +@ErrorStatus+ '-6051';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		
	END









GO
/****** Object:  StoredProcedure [dbo].[pInsertProgramType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUProgramType
Description: Inserts data to LUProgramType. This table matches the Program with the user.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertProgramType](
	@ProgramName Nvarchar(20),
	@ProgramDescription NVarchar(50),
	@ModifiedBy Name,
	@NewProgramTypeID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempProgramTypeID int
	
	SET @TempProgramTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

BEGIN TRY
	BEGIN TRANSACTION;
	/****************************************************************************/
	--This is a bit different than some procedures because there is a lookup table associated with 
	--the address, so we need to be sure that the data matches a program type before continuing.
	SELECT @TempProgramTypeID = ProgramTypeID 
	  FROM person.LUProgramType
	     WHERE ProgramName = Rtrim(Ltrim(@ProgramName)) --Be a bit paranoid and trim the input for white spaces
 

/****************************************************************************/	          
		IF @@Error <> 0 
		BEGIN
			SELECT @ErrorStatus = @@ERROR + ' -6040';
			SET @Success = 0;
		END
		 
		
	IF @TempProgramTypeID = 0 --If they don't exist in the database then
	  BEGIN
		
			  INSERT Person.LUProgramType(ProgramName,ProgramDescription,ModifiedDate, ModifiedBy)
					VALUES (@ProgramName,@ProgramDescription,SYSDATETIME(),@ModifiedBy)
				
				set @NewProgramTypeID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
	  END
		
		END TRY

		BEGIN CATCH
		  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
			--We only care if the error was not raised by SSE
			IF @@ERROR <> 50000
				BEGIN
					SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
				END
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus= @ErrorStatus +' -6041 Insert Failed on Program Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pInsertRace]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LURace
Description: Inserts data to LURace. This table matches the Race with a U.S Census race category
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertRace](
	@RaceAbbreviation NVarchar(10),
	@RaceDescription NVarchar(50),
	@ModifiedBy Name,
	@NewRaceID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempRaceID int
	
	SET @TempRaceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	          
BEGIN TRY
	BEGIN TRANSACTION;
/****************************************************************************/
	--This is a bit different than some procedures because there is a lookup table associated with 
	--the race, so we need to be sure that the data matches a race type before continuing. Hopefully, the
	--abbreviations will be consistent so that we do not have duplicates. There is no sure way to code this.
	--White, Black(AA or Negro).American Indian or Alaskan native.,Asian Indian,Chinese,Filipino, Other Asian, Japanese,
	--Korean, Vietnamese, Native Hawaiian, Guanamanian or Chamorro, Samoan, Other pacific Islander.
	SELECT @TempRaceID = RaceID 
	  FROM person.LURace
	     WHERE RaceAbbreviation = Rtrim(Ltrim(@RaceAbbreviation)) --Be a bit paranoid and trim the input for white spaces


/****************************************************************************/	
		IF @@Error <> 0 
		BEGIN
			SELECT @ErrorStatus = @@ERROR + '-6020';
			SET @Success = 0;
			RAISERROR(@ErrorStatus, 16,1);
		END
		 
		
	IF @TempRaceID = 0 --If they don't exist in the database then
		BEGIN
		
			  INSERT Person.LURace(RaceAbbreviation,RaceDescription, ModifiedDate,ModifiedBy)
					VALUES (@RaceAbbreviation,@RaceDescription,SYSDATETIME(),@ModifiedBy)
				
				set @NewRaceID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		END
END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6021 Insert Failed Race Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END









GO
/****** Object:  StoredProcedure [dbo].[pInsertSSN]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
*Author: Gary Savard
*Date: 15 Oct 10
*Table Name: SSN.SSN
Description: Inserts data to SSN. Only Certain federal programs require that SSN be captured, so we only want to
use this sparingly.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertSSN](
	@PersonID int,
	@SSN NVarchar(9),
	@ModifiedBy Name,
	@NewSSNID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int,
	@TempSSNID int
	
	SET @TempPersonId =0;
	SET @TempSSNID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		BEGIN TRY
		  BEGIN TRANSACTION;
		  SELECT @SSN = ltrim(rtrim(@SSN)); --Get rid of spaces before we begin!
		  /****************************************************************************/
			IF ((@PersonID = 0) OR (@PersonID IS NULL)) 
				BEGIN	
					SELECT @ErrorStatus = '-12005 PersonID cant be 0/NULL';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1); 
					
				END
			IF ((LEN(@SSN)<9) OR (@SSN IS NULL))
				BEGIN	
					SELECT @ErrorStatus = '-11006 Invalid SSN';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1); 
				
				END
			
			
			SELECT @TempPersonID = PersonID
				FROM Person.Person
					Where PersonID = @PersonID
					
			
			IF @TempPersonID = 0 OR @TempPersonID IS NULL
				BEGIN
					SELECT @ErrorStatus ='-12008 PersonID does not exist in Person';
					SET @Success=0;
					RAISERROR(@ErrorStatus,16,1);
				END	

			--Final check to be sure this is not a duplicate
			
			SELECT @TempSSNID = SSNID 
				FROM SSN.SSN
					WHERE PersonID = @PersonID AND SSN =@SSN
								
			IF @TempSSNID <> 0 
				--This already exists! Duplicate Row Error
				BEGIN
					SELECT @ErrorStatus = '-12009 Duplicate Row Exists';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END
				


			/****************************************************************************/	          
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '  -6060';
					SET @Success = 0;
					RAISERROR(@ErrorStatus,16,1);
				END
			 
				
				--If they don't exist in the database then
				
					
						INSERT SSN.SSN (PersonID,SSN,ModifiedDate, ModifiedBy)
							VALUES (@PersonID,@SSN,SYSDATETIME(),@ModifiedBy)
								
								SET @NewSSNID =@@IDENTITY;
								SET @success =1;
								SET @ErrorStatus =0;
								
						COMMIT TRANSACTION;
						
				
			END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT  @ErrorStatus= @ErrorStatus + 'SSN -12001';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pInsertState]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUState
Description: Inserts data to LUState. This table matches the State with a State ID for ties to County, City and Zip Code.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertState](
	@StateCode Nvarchar(2),
	@Name Nvarchar(50),
	@ModifiedBy Name,
	@NewStateID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempStateID int
	
	SET @TempStateID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

BEGIN TRY
	 BEGIN TRANSACTION;
	 /****************************************************************************/
	--This is a bit different than some procedures because we do not want duplicates in the table associated with 
	--the state, so we need to be sure that the data matches a state before continuing.
	SELECT @TempStateID = StateID 
	  FROM person.LUState
	     WHERE StateCode = Rtrim(Ltrim(@StateCode)) --Be a bit paranoid and trim the input for white spaces

/****************************************************************************/	          
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-6030';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16, 1);
			END
		IF @TempStateID <>0
			BEGIN
				SELECT @ErrorStatus = 'State Already exists -6037'
				SET @Success =0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
		
			  INSERT Person.LUState(StateCode,Name,ModifiedDate, ModifiedBy)
					VALUES (@StateCode,@Name,SYSDATETIME(),@ModifiedBy)
				
				set @NewStateID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
			 COMMIT TRANSACTION;
	
			
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus= @ErrorStatus + @@ERROR + '-6031 Insert Failed on State';--6030-6039 is for this table
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pInsertUpdateFoodShelfCertification]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Foodshelf.FoodShelfCertification
Description: Inserts  OR updates data to Foodshelf.FoodShelfCertification. This procedure sets the last date of client
	certification using the passed in PersonID. If the PersonID already exists in the Table, then the 
	SP will update that row to the "LastCertificationDate", Else it will Insert a new row.
	This stored procedure should only be called if the person needs to certify or recertify.
Revisions:28 March 11. GS added CertificationTextID
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pInsertUpdateFoodShelfCertification](
	@PersonID int,
	@LastCertificationDate Date,
	@CertificationTextID int,
	@ModifiedBy Name,
	@NewFoodShelfCertificationID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS

Set NoCount ON;


	DECLARE
	@TempFoodShelfCertificationID int;
	
	SET @TempFoodShelfCertificationID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
         


BEGIN TRY
/****************************************************************************/
	
	SELECT @TempFoodShelfCertificationID = FoodshelfCertificationID
	  FROM Foodshelf.FoodShelfCertification
	     WHERE Foodshelf.FoodShelfCertification.PersonID = @PersonID 

/****************************************************************************/	 
		
	IF @TempFoodShelfCertificationID = 0 --If they don't exist in the database then
	 
	   BEGIN
	  
	 	BEGIN TRANSACTION;
	 				IF @CertificationTextID = 0 or @CertificationTextID IS NULL
	 					BEGIN
	 						SET @Success = 0;
							SET @ErrorStatus ='-16005 CertificationTextID cannot be null/0';
							RAISERROR(@ErrorStatus,16,1);
	 					END
					IF @@Error <> 0 
						BEGIN
							SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-6040';
							SET @Success = 0;
							RAISERROR (@Errorstatus, 16,1);
						END
			
				INSERT Foodshelf.FoodShelfCertification(PersonID,CertificationTextID,LastCertificationDate,ModifiedDate, ModifiedBy)
					VALUES (@PersonID,@CertificationTextID,@LastCertificationDate,SYSDATETIME(),@ModifiedBy)
				
				set @TempFoodShelfCertificationID =@@IDENTITY;
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
			
		  
		END
	ELSE --The person exists so Update to the new certification date and verbiage.	
		BEGIN	
				IF @CertificationTextID = 0 or @CertificationTextID IS NULL
	 					BEGIN
	 						SET @Success = 0;
							SET @ErrorStatus ='-16005 CertificationTextID cannot be null/0';
							RAISERROR(@ErrorStatus,16,1);
	 					END
			
				BEGIN TRANSACTION;
						
					UPDATE Foodshelf.FoodShelfCertification
						SET LastCertificationDate = @LastCertificationDate,
							CertificationTextID = @CertificationTextID
						WHERE PersonID = @PersonID AND FoodShelfCertificationID = @TempFoodShelfCertificationID
				COMMIT TRANSACTION;
		END
	END TRY
	

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus = @ErrorStatus + ' -8001 Insert Fail ProgramSvcType';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH

		
	















GO
/****** Object:  StoredProcedure [dbo].[pInsertVolunteerContactInformation]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Gary Savard
-- Create date: 06/01/2011
-- Description:	Inserts volunteer contact information
-- =============================================
CREATE PROCEDURE [dbo].[pInsertVolunteerContactInformation] 
	-- Add the parameters for the stored procedure here
	@ContactFirstName Name,
	@ContactLastName Name,
	@ContactAddres1 NVarchar(50),
	@ContactAddress2 NVarchar(50)=NULL,
	@ContactHomePhone Phone,
	@ContactWorkPhone Phone,
	@ContactCellPhone Phone,
	@ContactPager Nvarchar(20),
	@ContactEmail NVarchar(50),
	@VolunteerTypeID int,
	@IsActive bit,
	@ModifiedBy Name,
	@VolunteerPersonID int Output,
	@Error NVarchar(50) Output,
	@ErrorNo int output,
	@Success bit Output
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE 

@ErrNo int =0,
@ErrMsg NVarchar(50)=''

BEGIN TRY

   	
	--Data is Valid, start the transaction
	BEGIN TRANSACTION
	
		INSERT  Volunteer.ContactInformation(
						VolunteerPersonID,
						ContactFirstName,
						ContactLastName,
						ContactAddress1,
						ContactAddress2,
						ContactEmail,
						ContactHomePhone,
						ContactCellPhone,
						ContactWorkPhone,
						ContactPager,
						Volunteertypeid,
						IsActive,
						ModifiedBy,
						ModifiedDate)
				
					VALUES
					(@VolunteerPersonID,
					 @ContactFirstName,
					 @ContactLastName,
					 @ContactAddres1,
					 @ContactAddress2,
					 @ContactEmail,
					 @ContactHomePhone,
					 @ContactCellPhone,
					 @ContactWorkPhone,
					 @ContactPager,
					 @VolunteerTypeID,
					 @IsActive,
					 @ModifiedBy,					
					 SYSDATETIME()
					 )
					 
			SELECT @ErrNo = @@ERROR
			
			IF @ErrNo <>0--<> Error!
				BEGIN
					RAISERROR(@ErrNo,16,0)
				END
			SET @Success =1;
			
			COMMIT TRANSACTION
			
			SELECT @VolunteerPersonID = @@IDENTITY
				
	
	
	END TRY
	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				
			  SET @Success =0;
			  
			 IF RTRIM(LTRIM(@errmsg)) =''
				 BEGIN
					SELECT @Error ='Failure in InsertPersonContactInformation Rollback'
				 END
			 ELSE
				BEGIN
					SELECT @Error = @ErrMsg
				END
			 
			 SET @ErrorNo = @ErrNo
			  
	END CATCH
   
END

GO
/****** Object:  StoredProcedure [dbo].[pInsertVolunteerEmergencyContactInformation]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gary Savard
-- Create date: 06/01/2011
-- Description:	Inserts volunteer emergency contact information
-- =============================================
create PROCEDURE [dbo].[pInsertVolunteerEmergencyContactInformation] 
	-- Add the parameters for the stored procedure here
	@VolunteerPersonID int,
	@ContactInformation NVARCHAR(MAX),
	@ModifiedBy Name,
	@EmergencyContactInformationID int Output,
	@Error NVarchar(50) Output,
	@ErrorNo int output,
	@Success bit Output
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE 

@ErrNo int =0,
@ErrMsg NVarchar(50)=''

BEGIN TRY

   		
	--Data is Valid, start the transaction
	BEGIN TRANSACTION
	
		IF @VolunteerPersonID =0 OR @VolunteerPersonID IS NULL
			BEGIN
				SELECT @ErrNo =999999
				SELECT @ErrMsg='VolunteerPersonID cannot be 0 or NULL'
				RAISERROR(@ErrNo,16,0)
			END
	
		INSERT  Volunteer.VolunteerEmergencyContact(
						VolunteerPersonID,
						ContactInformation,
						ModifiedBy,
						ModifiedDate)
				
					VALUES
					(@VolunteerPersonID,
					 @ContactInformation,
					 @ModifiedBy,					
					 SYSDATETIME()
					 )
					 
			SELECT @ErrNo = @@ERROR
			
			IF @ErrNo <>0--<> Error!
				BEGIN
					RAISERROR(@ErrNo,16,0)
				END
			SET @Success =1;
			
			COMMIT TRANSACTION
			
			SELECT @VolunteerPersonID = @@IDENTITY
				
	
	
	END TRY
	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				
			  SET @Success =0;
			  
			 IF RTRIM(LTRIM(@errmsg)) =''
				 BEGIN
					SELECT @Error ='Failure in InsertVolEmergencyContactInfo Rollback'
				 END
			 ELSE
				BEGIN
					SELECT @Error = @ErrMsg
				END
			 
			 SET @ErrorNo = @ErrNo
			  
	END CATCH
   
END
GO
/****** Object:  StoredProcedure [dbo].[pInsertVolunteerNotes]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gary Savard
-- Create date: 06/01/2011
-- Description:	Inserts volunteer Notes
-- =============================================
create PROCEDURE [dbo].[pInsertVolunteerNotes] 
	-- Add the parameters for the stored procedure here
	@VolunteerPersonID int,
	@Notes NVARCHAR(MAX),
	@ModifiedBy Name,
	@EmergencyContactInformationID int Output,
	@Error NVarchar(50) Output,
	@ErrorNo int output,
	@Success bit Output
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE 

@ErrNo int =0,
@ErrMsg NVarchar(50)=''

BEGIN TRY

   		
	--Data is Valid, start the transaction
	BEGIN TRANSACTION
	
		IF @VolunteerPersonID =0 OR @VolunteerPersonID IS NULL
			BEGIN
				SELECT @ErrNo =999999
				SELECT @ErrMsg='VolunteerPersonID cannot be 0 or NULL'
				RAISERROR(@ErrNo,16,0)
			END
	
		INSERT  Volunteer.VolunteerNotes(
						VolunteerPersonID,
						Note,
						ModifiedBy,
						ModifiedDate)
				
					VALUES
					(@VolunteerPersonID,
					 @Notes,
					 @ModifiedBy,					
					 SYSDATETIME()
					 )
					 
			SELECT @ErrNo = @@ERROR
			
			IF @ErrNo <>0--<> Error!
				BEGIN
					RAISERROR(@ErrNo,16,0)
				END
			SET @Success =1;
			
			COMMIT TRANSACTION
			
			SELECT @VolunteerPersonID = @@IDENTITY
				
	
	
	END TRY
	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				
			  SET @Success =0;
			  
			 IF RTRIM(LTRIM(@errmsg)) =''
				 BEGIN
					SELECT @Error ='Failure in InsertVolNotes Rollback'
				 END
			 ELSE
				BEGIN
					SELECT @Error = @ErrMsg
				END
			 
			 SET @ErrorNo = @ErrNo
			  
	END CATCH
   
END
GO
/****** Object:  StoredProcedure [dbo].[pUpdateAddress]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO









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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Address
Description: Updates data to Address table.This table has the possibility of duplicate rows because
	persons can have more than one address. We can check to see if an address is a duplicate, but that will have
	limited use since we would have to count on a combination of free-format fields since it is possible to have more than
	one address in the same city, zipcode, state, county, etc.
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pUpdateAddress](
	@PersonID int =0,--Having a default may seem strange for a mandatory field but it is here only to deal with NULL, if one should occur. 
	@AddressID int =0,--Having a default may seem strange for a mandatory field but it is here only to deal with NULL, if one should occur.
	@AddressLine1 Nvarchar(60),
	@AddressLine2 Nvarchar(60) = NULL,
	@City NVarchar(30),
	@County NVarchar(30),
	@State NVarchar(2),
	@PostalCode NVarchar(10) ,
	@AddressTypeID int,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempAddressTypeID int,
	@TempPersonID int,
	@TempAddressID int
	
	SET @TempAddressTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempAddressID =0;
	SET @TempAddressID = 0;		
/*The personID and AddressID must be non-zero because they are needed to update the row. If either is zero, we
exit the update*/
BEGIN TRY
	BEGIN TRANSACTION;
	IF ((@PersonID = 0) OR (@PersonID IS NULL)) OR ((@AddressID =0) OR (@AddressID IS NULL))
		BEGIN
			SET @ErrorStatus = ' -7014. PersonID, AddressID cannot be zero or null for update';
			RAISERROR(@ErrorStatus, 16,1);
		END



/****************************************************************************/
	--This is a bit different than some procedures because there is a lookup table associated with 
	--the address, so we need to be sure that the data matches an address type before continuing.
	SELECT @TempAddressTypeID = AddressTypeID 
	  FROM person.LUAddressType
		 WHERE AddressTypeID = @AddressTypeID --Be a bit paranoid and trim the input for white spaces
	
	If @TempAddressTypeID = 0
	BEGIN
		SET @ErrorStatus = ' -7002 Address Type does not exist in LUAddressType, Cannot Update'; --Failed in lookup table
		RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
		
	END	
	

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

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = @@ERROR + '-7000 pUpdateAddress';
		SET @Success = 0;
		RAISERROR (@ErrorStatus,16,1);
	END
	 
		
	
			  Update Person.Address
					SET PersonID = @PersonID,
						AddressLine1 = @AddressLine1,
						AddressLine2 =@AddressLine2,
						City = @City,
						State = @State,
						PostalCode = @PostalCode,
						AddressTypeID = @AddressTypeID,
						ModifiedDate = SYSDATETIME(),
						ModifiedBy = @ModifiedBy
					WHERE
						PersonID= @PersonID AND AddressID = @AddressID;
								
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			 SELECT @ErrorStatus =@ErrorStatus + ' -7012' +' Update Failed on Address';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END









GO
/****** Object:  StoredProcedure [dbo].[pUpdateAddressType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUAddressType
Description: Update data to LUAddressType. This table matches the address with an address type
Revisions:
G.S. - 20 Oct 10. Fixed problem with error handler not firing on preliminary lookup.
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pUpdateAddressType](
	@AddressTypeID int,
	@AddressType Nvarchar(10),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

BEGIN
	DECLARE
	@TempAddressTypeID int
	
	SET @TempAddressTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		
	

		BEGIN TRY
			BEGIN TRANSACTION;
		
			/****************************************************************************/
				--Avoid Duplicate Rows! However, a typo on input such as 'Hmoe' instead of 'Home' will do an isert.
				--Can't avoid finger problems!
				
			SELECT @TempAddressTypeID = AddressTypeID 
			  FROM person.LUAddressType
				 WHERE AddressTypeID = @AddressTypeID 
				 
			If @TempAddressTypeID = 0 --Cant Update if it doesnt exist
				BEGIN
					SELECT @ErrorStatus = '-6015 Address Type Does Not Exists';
					SET @Success =0;
					RAISERROR(@ErrorStatus, 16, 1);
				END

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

			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = Convert (nVarchar(50),@@ERROR) + ' -6010';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16, 1);
				END
	 
			
			 UPDATE Person.LUAddressType
				SET AddressType = @AddressType,
					ModifiedBy = @ModifiedBy,
					ModifiedDate = SYSDATETIME()
				WHERE 
					AddressTypeID =@AddressTypeID;
					
			
				
				set @success =1;
				set @ErrorStatus ='';
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
		
			  SET @Success =0;
			  SELECT  @ErrorStatus = @ErrorStatus + 'Update Failed Rollback -6011';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		

END








GO
/****** Object:  StoredProcedure [dbo].[pUpdateCertificationText]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







/*************************************************************************************************
*Author: Gary Savard
*Date: 3/29/2011
*Table Name: LUertificationText
Description: Update data to LUCertificationText.
This updates the LUCertificationText table. The updates should only be done to correct errors and only by an 
ageny designated representative.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateCertificationText](
	@CertificationTextID int,
	@CertificationText NVarchar(MAX),
	@GuidelinesText NVarchar(MAX),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCertificationTextID int
	
	SET @TempCertificationTextID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			IF (@CertificationTextID =0) --Must have a non zero value!
				BEGIN
					SELECT @ErrorStatus =  '-60055 CertificationTextID cannot be NULL or 0';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
	
/****************************************************************************/
			--Double check to see that we can find it in the LUCertificationText table before changing things
			SELECT @CertificationTextID = CertificationTextID 
				FROM Foodhself.LUCertificationText
					WHERE CertificationTextID = @CertificationTextID
					
	     		If (@TempCertificationTextID = NULL) OR (@TempCertificationTextID= 0) 
					BEGIN
						SET @ErrorStatus = ' -60052 CertificationTextID Doesnot Exist in LUCertificationText'; 
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
		
					END	

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

			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60050';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
			 --StateID is not updated because that should not change!
			  UPDATE Foodshelf.LUCertificationText
				SET CertificationText = @CertificationText,
					GuidelinesText = @GuidelinesText,
					ModifiedBy = @ModifiedBy,
					ModifiedDate = SYSDATETIME()
				WHERE
					CertificationTextID = @CertificationTextID 					
			  	set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60051 Update Failed on CertificationText ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateCity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUCity
Description: Update data to LUCity.
The CityID and StateID must not be 0 when passed in. Both are needed to make the tie.
Ideally we would have information on the county as well as the state before we add the city. However, 
we cannot assume that we have a county, so we will have it to default to 0, if no value is entered.
Revisions:
GS 20 Oct fixed failure in error handler due to implicit conversion of @@Error, worked intermittantly 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateCity](
	@CityID int,
	@CityName NVarchar(30),
	@CityAbbreviation Nvarchar(30) ='',
	@StateID int,
	@CountyID int = 0,--Default countyID to 0 just in case it comes in later. 
	@PostalCodeID int =0,--Might be Zero..
	@ModifiedBy Name,
	@NewCityID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCityID int
	
	SET @TempCityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			IF (@CityID =0) or (@StateID) = 0 --Must have a state AND city to update!
				BEGIN
					SELECT @ErrorStatus =  '-60055 StateID/CityID cant be NULL or 0';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
	
/****************************************************************************/
			--Double check to see that we can find it in the LUCity table before changing things
			SELECT @TempCityID = CityID 
				FROM person.LUCity
					WHERE CityID = @CityID and StateID = @StateID
					
	     		If (@TempCityID = NULL) OR (@TempCityID= 0) 
					BEGIN
						SET @ErrorStatus = ' -60052 City Doesnt Exist in LUCity'; 
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
		
					END	

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

			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60050';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
			 --StateID is not updated because that should not change!
			  UPDATE Person.LUCity
				SET CountyID = @CountyID,
					PostalCodeID = @PostalCodeID,
					CityName = @CityName,
					CityAbbreviation= @CityAbbreviation,
					ModifiedBy = @ModifiedBy,
					ModifiedDate = SYSDATETIME()
				WHERE
					STATEID = @StateID and CITYID = @CityID--Could just use City ID
					
			  	set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60051 Update Failed on City ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END
END









GO
/****** Object:  StoredProcedure [dbo].[pUpdateClientFamilyRecord]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






-- =============================================
-- Author:		Gary Savard
-- Create date: 26 Oct 2010
-- Description:	This is the main stored procedure to update a  family member for a client
-- in the system. It calls several other stored procedures to do updates into 
-- selected parts of the DB. Clients and Family members of clients have similar data, but 
--will use separate stored procedures for clarity. A note can either be a new note or an update to an exising one. If it is a new note, then
--the IsNewNoteflag must be passed in with 1 as value.
--FOOD. Same idea with the rest of the programs.
--IDs that are important such as 'address type' from that lookup table need to be passed in here since they
--were selected by the user. No need to try to figure them out in the SP
--Certification has its own button so we have a separate stored procedure to deal with that functionality and the same for 
--family members since they do not have some of the information that we need for the client. 

--Revisions: 4 Nov 10- Added Client notes insert procedure call
--          13 Dec 10- Added Gender to Update Demographics call
--			1 April 11 - Removed some fields based on Champlain Charity requirements. Added some fields.
--          5 April remove @numberInHousehold, @HomeboundDelivery,@ISPrimaryLanguage,@LanguageId,@Title,@Suffix,@AddressId,@PhoneID 
--			11 July 11, Added RTRIM, LTRIM to client's name
-- =============================================
CREATE PROCEDURE [dbo].[pUpdateClientFamilyRecord] (
	@RecordSource NVarchar(8),
	@FamilyRelationshipID int,--This is how we know whicy person is being updated, we do not want dupes in the system. A person should be in the familyRelationship table 0to1 times
	@PersonID int, --This is the family member that we will be updating
	@ClientPersonID int,--This is the client to whom the family member belongs
    @DemographicsID int,
    @NotesID int =0,
   	@FirstName Name,
	@MiddleName Name = NULL,
	@LastName Name,
	@DateOfBirth DateTime,
	@RelationshipID int,
	@RelationshipDescription NVarchar(50)='',
	@FamilyStatusType NVarchar(50),
	@HousingStatus nVarchar(50),--The TEXT value from the lookup table. Saves having to query by ID later
	@Disability NoYesMaybe =0,
	@Gender NVarchar(2)='',--Foodshelf and WX may leave blank
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe =0 ,
	@InsuranceType NVarchar(50),
	@FoodStamps NoYesMaybe =0,--Three squares
	@EducationCategoryID int =0, --Not required for Food shelf
	@CountryOfOrigin nVarchar(70)='', --Not required for food shelf
	@Race NVarchar(20) =NULL,
	@Ethnicity NVarchar(20) =NULL, 
	@IncomeSourceID int =0,
	@IsNewNote bit=0,
	@Notes NVarchar(MAX)=NULL,--A single person may have many notes. The notes will be specific to a particular program, so we will not have a single notes table
	@ModifiedBy Name,
	@NewHouseholdNotesID int Output,--This is only used if there is a new note sent in with the record.
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
	

SET NOCOUNT ON;
	DECLARE
	@ValidSource int,
	@TempPersonID int,
	@Succ bit,
	@ErrorMsg NVarchar(50),
	@NewClientNotesID int,
	@TempClientPersonID int,
	@TempFamilyRelationshipID int,
	@TempIncomeSourceCount int,
	@TempIncomeSourceID int,
	
	@DummyNumberInHousehold int, --just place holder with default of 0
	@DummyHomeboundDelivery int,
	@DummyIsPrimaryLanguage bit,
	@DummyLanguageID int,
	@DummyTitle NVarchar(8),
	@DummySuffix NVarchar(10),
	@DummyEmailAddress NVarchar(50),
	@DummyEmailContactPreference bit,
	@DummyAddress1 NVarchar (60),
	@DummyAddress2 NVarchar (60),
	@DummyCity NVarchar (30),
	@DummyState NVarchar(2),
	@DummyPostalCode NVarchar(10),
	@DummyAddressTypeID int,
	@DummyPhoneNumber Phone,
	@DummyPhoneExtension Nvarchar(8),
	@DummyPhoneTypeID int
	
	
			
	
	SET @ValidSource =0;
	SET @TempPersonID =0;
	SET @NewClientNotesID =0;
	SET @Succ =0;
	SET @ErrorMsg ='';
	SET @TempClientPersonID =0;
	SET @TempFamilyRelationshipID =0;
	SET @TempIncomeSourceCount =0;
	SET @TempIncomeSourceID =0;
	
	
	SET @DummyNumberInHousehold =0;
	SET @DummyHomeboundDelivery=2;--This is set to N/A
	SET @DummyIsPrimaryLanguage=0;
	SET @DummyLanguageID=0;
	SET @DummyTitle = NULL;
	SET @DummySuffix = NULL;
	SET @DummyEmailAddress =NULL;
	SET @DummyEmailContactPreference =0;
	SET @DummyAddress1 =NULL;
	SET @DummyAddress2 =NULL;
	SET @DummyCity = NULL;
	SET @DummyState =NULL;
	SET @DummyPostalCode =NULL;
	SET @DummyAddressTypeID =0;
	SET @DummyPhoneNumber =NULL;
	SET @DummyPhoneExtension =NULL;
	SET @DummyPhoneTypeID =0;
	SET @FirstName = LTRIM(RTRIM(@FirstName));
	SET @MiddleName = LTRIM(RTRIM(@MiddleName));
	SET @LastName = LTRIM(RTRIM(@LastName));
		
 BEGIN TRY
	BEGIN TRANSACTION;
	
	
	--Take the return value and throw error if 0 because we cannot proceed of we don't know
	--which set of sps to call.
	SET @ValidSource = DBO.ValidateDataSource(@RecordSource);
	
	IF @ValidSource =0
		BEGIN
			SET @Success =0;
			SELECT @ErrorStatus = '-18100 Invalid Record source';
			RAISERROR(@ErrorStatus,16,1);
			--Raise Error Here because the source is unknown.
		END
	
	
	
	--The family member must be associated with a ClientPersonID or we bail.
	
		IF @FamilyRelationshipID =0 OR @FamilyRelationshipID IS NULL--Can't update if this is not valid!
			BEGIN
				SET @Success =0;
				SET @ErrorStatus ='-185002 FamilyRelationshipID cant be 0/NULL';
				RAISERROR (@ErrorStatus,16,1);
			END
		
		SELECT @TempFamilyRelationshipID = FamilyRelationshipID	
			FROM Person.FamilyRelationships
				WHERE FamilyRelationshipID = @FamilyRelationshipID
				
		IF @TempFamilyRelationshipID = 0 OR @TempFamilyRelationshipID IS NULL
			BEGIN
				SET @Success =0
				SET @ErrorStatus ='-185003 Record not found FamilyRelationships';
				RAISERROR (@ErrorStatus,16,1);
				
			END
		IF @PersonID =0 or @PersonID IS NULL
			BEGIN
				SET @Success =0;
				SET @ErrorStatus = '-185004 PersonID cant be 0/NULL';
				RAISERROR(@ErrorStatus,16,1);
			END
			
		SELECT @TempPersonID = @PersonID
			FROM Person.Person
				WHERE PersonID = @PersonID
		
		IF @TempPersonID = 0 OR @TempPersonID IS NULL
			BEGIN
				SET @Success = 0;
				SET @ErrorStatus = '-185005 Person Doesnt exist in Person';
				RAISERROR(@ErrorStatus,16,1);
			END
	
			IF @ClientPersonID = 0 OR @ClientPersonID IS NULL
			BEGIN
				SET @Success =0;
				SET @ErrorStatus = '-18500 Client does not exist in Person';
				RAISERROR(@ErrorStatus,16,1);
			
			END	
			
			SELECT	@TempClientPersonID = PersonID
				FROM Person.Person
					WHERE PersonID = @PersonID
					
			IF @TempClientPersonID = 0 OR @TempClientPersonID IS NULL
			BEGIN
				SET @Success = 0;
				SET @ErrorStatus = '-185005 Person Doesnt exist in Person';
				RAISERROR(@ErrorStatus,16,1);
			END
					
					
	
				
	--Update Person.	
	BEGIN
		EXEC DBO.pUpdatePerson @PersonID,@DummyTitle,@FirstName,@MiddleName,@LastName,@DummySuffix,@DateOfBirth,@DummyEmailAddress,@DummyEmailContactPreference,@ModifiedBy,@Succ OUTPUT,@ErrorMsg OUTPUT;
				
		IF @Succ =0 -- Failure!
			BEGIN
				SET @Success = @Succ;
				SELECT @ErrorStatus = '-18200 Sub Pro UpdatePerson Fail'+ @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
			END
		SET @Success =1;
		SET @ErrorStatus='';	
	END
	
	--IF the source is from Food Shelf we cannot assume that we will need to call the address or phone SPs because they 
	--are not required to take that information. We will consider a NULL or 0 ID in AddressID to mean that this is a Foodshelf
	
	
	--The address should be the same as that of the client, but we will add it anyway because this person
	--may eventually become a client and we will already have an AddressID that we can use and modify the location.

		
		BEGIN
			--Commented out because this needs some thought as we go into alpha testing
			--IF ((@RecordSource <> 'FOOD') AND (LTRIM(RTRIM(@Address1)) ='') OR (LTRIM(RTRIM(@Address1)) IS NULL) )--This is a problem because address is required
			--	BEGIN
			--		SET @Succ =0;
			--		SET @ErrorStatus ='-18300 Address Required for Non foodshelf intake.';
			--		RAISERROR(@ErrorStatus,16,1);
			--	END
		--The family member is at the same address as the client so we do not put them in the address table. Query them from the family relationship
		--IF ((@AddressID <>0) AND (@AddressID IS NOT NULL))
		-- BEGIN	
		--	EXEC DBO.pUpdateAddress @PersonID,@AddressID,@DummyAddress1,@DummyAddress2,@DummyCity,@DummyCounty,@DummyState,@DummyPostalCode,@DummyAddressTypeID,@ModifiedBy, @Succ Output, @ErrorMsg Output ;	
			
		--	IF @Succ =0 --Failed, Rollback!
		--		BEGIN
		--			SET @Success =0;
		--			SELECT @ErrorStatus = '-18200 Sub proc Update Address returned error' + @ErrorMsg;
		--			RAISERROR (@ErrorSTatus, 16,1);
		--		END
				
		--END

	--This has been removed because Champlain Charity does not collect family member phone numbers
	--Insert Phone Number
	--We allow phone number since they may have a cell.
	--BEGIN
	--	--May need in future
	--	--IF ((@RecordSource <> 'FOOD') AND (LTRIM(RTRIM(@PhoneNumber)) ='') OR (LTRIM(RTRIM(@PhoneNumber)) IS NULL) )--This is a problem because Phone Number is required
	--	--	BEGIN
	--	--				SET @Succ =0;
	--	--				SET @ErrorStatus ='-17400 Phone Number Required for Non foodshelf intake.';
	--	--				RAISERROR(@ErrorStatus,16,1);
	--	--	END
			
	--	IF (@PhoneID<>0) AND (@PhoneID IS NOT NULL)
	--		BEGIN
	--			EXEC DBO.pUPdatePhone @PhoneID,@PersonID,@PhoneNumber,@PhoneExtension,@PhoneTypeID,@ModifiedBy, @Succ output, @ErrorMsg output ;
	--		END
			
	--		IF @Succ =0
	--			BEGIN
	--				SET @Success =0;
	--				SELECT @ErrorStatus = '-18200 Sub proc Update Phone returned fail' + @ErrorMsg;
	--				RAISERROR(@ErrorStatus, 16,1);
	--			END
	--END
	
	--Insert Demographics
	BEGIN
		EXEC dbo.pUpdateDemographics @DemographicsID,@PersonID,@EducationCategoryID ,@HousingStatus,@DummyNumberInHousehold,@Gender,@Race,@CountryOfOrigin,@Ethnicity,@Disability,@CSFP,@Veteran,@HealthInsurance,@InsuranceType,@FamilyStatusType,@FoodStamps,@DummyHomeboundDelivery,@ModifiedBy,@Succ OUTPUT, @ErrorMsg OUTPUT; 
		
		IF @Succ = 0
			BEGIN
				SET @Success =0;
				SELECT @ErrorStatus ='-18200 Sub proc Update Demographics returned fail' + @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
				
			END
		END
		
		--Income source may could possibly be ID 0 which would not be updated since that indicates no selection. This will require a sp at some point
		--because there may be >1 income source. For now, we have a 1 to 1 relationship between person and income source. Yup, using a table scan for the
		--aggregate, but this will be chaning with future sp
		IF EXISTS(SELECT * from Person.Income WHERE PersonID=@PersonID) AND (@IncomeSourceID>0)--Assuming that a good IncomeSourceID is passed in.
			BEGIN
				Update Person.Income 
						SET IncomeSourceID = @IncomeSourceID,
							ModifiedBy = @ModifiedBy,
							ModifiedDate = SYSDATETIME()
						WHERE PersonID = @PersonID;
				IF @@ERROR >0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus ='-18200 Sub proc insert income returned fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus,16,1);
				END	
			END--End IF
			
		ELSE
			BEGIN
				IF (@IncomeSourceID >0)--Only insert if there is a valid IncomeSourceId coming in --only works if we have 1 to 1 relationship and that is all we have for now
				BEGIN
					INSERT INTO PERSON.Income (IncomeSourceID, PersonID, ModifiedBy, ModifiedDate) VALUES (@IncomeSourceID,@PersonID,@ModifiedBy,SYSDATETIME());
				END
				
			IF @@ERROR >0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus ='-18200 Sub proc insert income returned fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus,16,1);
				END	
			END--End else
			
		
		
	--Insert Client Notes if they exist. This insert procedure is for the client, so we do not have
	--A value for HouseholdMemberPersonID so we hard code it to 0.
		
		IF (@IsNewNote =1) AND LTRIM(RTRIM(@Notes)) <> ''
		BEGIN
			EXEC DBO.pInsertHouseholdNotes @ClientPersonID,@PersonID, @Notes,@ModifiedBy,@NewHouseholdNotesID,@Succ OUTPUT,@ErrorMsg OUTPUT;
			 IF @Succ =0
			 BEGIN
				SET @Success =0;
				SET @ErrorStatus ='-18001 New Note Insert Failed';
				RAISERROR(@ErrorStatus,16,1);
			 END
			 SET @Success =1;
			 SET @ErrorStatus ='';
		
		END
		
		IF (@IsNewNote = 0) AND (@NotesID)<>0 AND @NotesID IS NOT NULL
			BEGIN
				EXEC DBO.pUpdateHouseholdNotes @NotesID,@ClientPersonID,@PersonID,@Notes,@ModifiedBy,@Succ OUTPUT,@ErrorMsg OUTPUT;
				IF @Succ =0
				BEGIN
					SET @Success =0
					SET @ErrorStatus = '-18200 Update Failed Notes' + @ErrorMsg;
					RAISERROR(@ErrorStatus,16,1);
				END
			
			END
		
	--We have everything except for the relationship to the client, so we do that last.
	 
		
			EXEC DBO.pUpdateFamilyRelationship @FamilyRelationshipID,@PersonID, @ClientPersonID,@RelationshipID,@RelationshipDescription,@ModifiedBy,  @Succ OUTPUT, @ErrorMsg OUTPUT; 
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SET @ErrorStatus ='-17001 Insert Failed Family Relationship'+ @ErrorMsg
					RAISERROR(@ErrorStatus,16,1);
				END	
		
			
	

		
	--We are using nested transactions to make sure one exists in case 
	--of a rollback in subordinate Stored Procedure
	IF @@TRANCOUNT > 0 
		BEGIN
			SET @Success =1;
			SET @ErrorStatus='';
			COMMIT TRANSACTION;
		END
END
END TRY
	
BEGIN CATCH
	IF @@TRANCOUNT >0
		BEGIN
		SET @Success =0
		SET @ErrorStatus =@ErrorStatus + '  ' +@@Error
			ROLLBACK TRANSACTION;
			
		RAISERROR(@ErrorStatus,16,1);
		END
END CATCH

 
    
	














GO
/****** Object:  StoredProcedure [dbo].[pUpdateClientRecord]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		Gary Savard
-- Create date: 26 Oct 2010
-- Description:	This is the main stored procedure to Update a new client
-- into the system. It calls several other stored procedures to do Updates into 
-- selected parts of the DB. Clients and Family members of clients have similar data, but 
--will use separate stored procedures for clarity.
--When updating we have to make some assumptions for food shelf.IF the client is in and their address has changed,
--we have to assume that the input FoodTypeGiven is for the current visit, so we do not update that. Instead, we insert a new
--row for the current visit.
--@RecordSource can be FOOD,WX,MICRO,TENANT,COMMACT,ADMIN. This will be used to only execute parts of the 
--SP relevant to the client intake data brought in. For example, Foodshelf requires that a record be 
--set for the type of food taken, but this is not required elsewhere so we only execute that SP If things come from 
--FOOD. Same idea with the rest of the programs.
--IDs that are important such as 'address type' from that lookup table need to be passed in here since they
--were selected by the user. No need to try to figure them out in the SP
--Certification has its own button so we have a separate stored procedure to deal with that functionality and the same for 
--family members since they do not have some of the information that we need for the client. 
--4 April 2011. Added multiple addresses, FamilyStatusType, Insurance Type,Changed AddressTypeID to int
--19 April 2011 - Addes @IsUpdateBreadGroceries. If this is 1 then that SP is executed.
--19 July 2011- Added RTRIM, LTRIM to client name.
CREATE PROCEDURE [dbo].[pUpdateClientRecord] (
	@PersonID int,
	@HouseHoldPersonID int =0,--This will be null or zero on input if this is a client and not a family member
	@PhysicalAddressID int,
	@MailAddressID int,
	@DemographicsID int,
	@PhoneID1 int,
	@PhoneID2 int,	
	@RecordSource NVarchar (8), --This allows for the sub sp's to be executed or skipped based on what data is to be saved
	@Title NVarchar(8) =NULL,
	@FirstName Name,
	@MiddleName Name = NULL,
	@LastName Name,
	@Suffix NVarchar(10) = NULL,
	@Gender NVarchar(2) = NULL,
	@DateOfBirth DateTime,
	@PhysicalAddress1 NVarchar(60) =NULL,--Only for Foodshelf!!
	@PhysicalAddress2 NVarchar(60) = NULL,
	@PhysicalCity	NVarchar(30),
	@PhysicalCounty NVarchar(30) = NULL,
	@PhysicalState NVarchar(2),
	@PhysicalPostalCode NVarchar(10),
	@PhysicalAddressTypeID  int,--From the Lookup based on user input. May not need if Foodshelf
	@MailAddress1 NVarchar(60) =NULL,--Only for Foodshelf!!
	@MailAddress2 NVarchar(60) = NULL,
	@MailCity	NVarchar(30),
	@MailCounty NVarchar(30) = NULL,
	@MailState NVarchar(2),
	@MailPostalCode NVarchar(10),
	@MailAddressTypeID  int,
	@EmailAddress Nvarchar(50) = NULL,
	@EmailContactPreference NoYes =0,
	@PhoneNumber Phone ='',
	@PhoneExtension Nvarchar(8) ='', --may not be implemented yet
	@PhoneTypeID int =0, --Food shelf again!
	@PhoneNumber2 Phone ='',
	@PhoneExtension2 Nvarchar(8) ='',
	@PhoneTypeID2	 int =0,
	@FamilyStatusType NVarchar(50),
	@HousingStatus nVarchar(50),--The TEXT value from the lookup table. Saves having to query by ID later
	@Disability NoYesMaybe =0,
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe =0 ,
	@InsuranceType NVarchar(50),
	@FoodStamps NoYesMaybe =0,--Three squares
	@HomeboundDelivery NoYesMaybe =0,
	@LanguageID int =0,--This is only important for volunteers and that funtionality has not been developed yet.
	@IsPrimaryLanguage bit =0,
	@EducationCategoryID int =0, 
	@CountryOfOrigin nVarchar(70)='', 
	@Race NVarchar(20) =NULL,
	@Ethnicity NVarchar(20) =NULL, 
	@NumberInHousehold int,
	@IncomeSourceID int =0,
	@HouseholdNotesID int=0, --Necessary if this is an existing note. Default to 0 if new note to avoid NULLs
	@Notes NVarchar(MAX)=NULL,--A single person may have many notes. The notes will be specific to a particular program, so we will not have a single notes table
	@IsNewNote bit,
	@FoodGiven FoodShelf.GroceryOrBreadProduce,
	@FoodReceivedDate DateTime,
	@IsUpdateBreadGroceries int,--Only if the client came in for these items
	@ModifiedBy Name,
	@NewPhysicalAddressID int Output,
	@NewMailAddressID int Output,
	@NewPhoneID int Output,
	@NewPhoneID2 int Output,
	@NewHouseholdNotesID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
	

SET NOCOUNT ON;
	DECLARE
	@ValidSource int,
	@CheckPersonID int,
	@CheckAddressID int,
	@CheckPhoneID int,
	@Succ bit,
	@ErrorMsg NVarchar(50),
	@CheckDemographicsID int, --Not using here, just a place holder!
	@NewFoodTypeGivenID int -- We don't do anything with this. Just receives SP output for now.
	
	SET @ValidSource =0;
	SET @CheckPersonID =0;
	SET @CheckAddressID =0;
	SET @CheckPhoneID = 0;
	SET @CheckDemographicsID =0;
	SET @NewFoodTypeGivenID =0;
	SET @Succ =0;	
	SET @Success =1;
	SET @ErrorMsg ='';
	SET @FirstName = LTRIM(RTRIM(@FirstName));
	SET @MiddleName = LTRIM(RTRIM(@MiddleName));
	SET @LastName = LTRIM(RTRIM(@LastName));
	
BEGIN		
 BEGIN TRY
	BEGIN TRANSACTION;
	
	
	--Take the return value and throw error if 0 because we cannot proceed of we don't know
	--which set of sps to call.
	SET @ValidSource = DBO.ValidateDataSource(@RecordSource);
	
	IF @ValidSource =0
		BEGIN
			SET @Success =0;
			SELECT @ErrorStatus = '-13100 Invalid Record source';
			RAISERROR(@ErrorStatus,16,1);
			--Raise Error Here because the source is unknown.
		END
		
	--Check to see if the person is in the DB. IF not, we are going to bail!
	BEGIN
		SELECT @CheckPersonID = PersonID
			FROM Person.Person
				WHERE PersonID = @PersonID
		IF @CheckPersonID = 0 OR @CheckPersonID IS NULL -- Not Good! Bail out!
			BEGIN
				SET @Success = 0;
				SET @ErrorStatus = '-1005 PersonId cant be 0/Null';
				RAISERROR(@ErrorStatus,16,1);
			END
					
		EXEC DBO.pUpdatePerson @PersonID,@Title,@FirstName,@MiddleName,@LastName,@Suffix, @DateOfBirth,@EmailAddress,@EmailContactPreference,@ModifiedBy,@Succ Output, @ErrorMsg Output;
		
		IF @Succ =0 -- Failure!
			BEGIN
				SET @Success = @Succ;
				SELECT @ErrorStatus = '-13200 Sub Pro update person Fail'+ @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
			END
	END
	
	--IF the source is from Food Shelf we cannot assume that we will need to call the address or phone SPs because they 
	--are not required to take that information.
	--IF we have a good PersonID returned, we continue to Address
	

		--The record we are updating may have been originally from FoodShelf so we may not have an address. If the AddressID is 0
		--and the @address1 is not blank, we will insert an address. If We have an AddressID that is > 0, we will continue with 
		--an update and not an insert.
		IF  (@PhysicalAddressID = 0 OR @PhysicalAddressID IS NULL) AND ((LTRIM(RTRIM(@PhysicalAddress1)) <> '') AND (@PhysicalAddress1 IS NOT NULL))
		 BEGIN	
			EXEC DBO.pInsertAddress @PersonID, @PhysicalAddress1,@PhysicalAddress2, @PhysicalCity,@PhysicalCounty,@PhysicalState,@PhysicalPostalCode,@PhysicalAddressTypeID,@ModifiedBy, @NewPhysicalAddressID Output,@Succ Output, @ErrorMsg Output ;	
			
			IF @Succ =0 --Failed, Rollback!
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc call Insert PhysAddress returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1);
				END
			
		END
			
	   ELSE IF @PhysicalAddressID >0 --Slam the record in if it exists.
	          BEGIN
					SELECT @CheckAddressID = AddressID
						FROM Person.Address
							WHERE
								AddressID = @PhysicalAddressID
								
					IF @CheckAddressID = 0 OR @CheckAddressID IS NULL --Something is wrong! Bail!
					  BEGIN
						SET @Success =0;
						SET @ErrorStatus = '-7014 Invalid PhysicalAddressID update failed';
						RAISERROR(@ErrorStatus,16,1);
					  END			
								
								
				EXEC DBO.pUpdateAddress @PersonId, @PhysicalAddressID, @PhysicalAddress1, @PhysicalAddress2, @PhysicalCity,@PhysicalCounty,@PhysicalState,@PhysicalPostalCode,@PhysicalAddressTypeID,@ModifiedBy,@Succ output,@ErrorMsg output;
			
				IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc call Update PhysAddress returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1);
				END
			END
	--One more time through this logic for mailing address
		IF  (@MailAddressID = 0 OR @MailAddressID IS NULL) AND ((LTRIM(RTRIM(@MailAddress1)) <> '') AND (@MailAddress1 IS NOT NULL))
		 BEGIN	
			EXEC DBO.pInsertAddress @PersonID, @MailAddress1,@MailAddress2, @MailCity,@MailCounty,@MailState,@MailPostalCode,@MailAddressTypeID,@ModifiedBy, @NewMailAddressID Output,@Succ Output, @ErrorMsg Output ;	
			
			IF @Succ =0 --Failed, Rollback!
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc call Insert Address returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1);
				END
			
		END
			
	   ELSE IF @MailAddressID >0 --Slam the record in if it exists.
	          BEGIN
					SELECT @CheckAddressID = AddressID
						FROM Person.Address
							WHERE
								AddressID = @MailAddressID
								
					IF @CheckAddressID = 0 OR @CheckAddressID IS NULL --Something is wrong! Bail!
					  BEGIN
						SET @Success =0;
						SET @ErrorStatus = '-7014 Invalid MailAddressID update failed';
						RAISERROR(@ErrorStatus,16,1);
					  END			
								
								
				EXEC DBO.pUpdateAddress @PersonId, @MailAddressID, @MailAddress1, @MailAddress2, @MailCity,@MailCounty,@MailState,@MailPostalCode,@MailAddressTypeID,@ModifiedBy,@Succ output,@ErrorMsg output;
			
				IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc call Update Address returned error' + @ErrorMsg;
					RAISERROR (@ErrorSTatus, 16,1);
				END
			END

	--Insert or update Phone Number same rules as for Address
		IF @PhoneID1 = 0 OR @PhoneID1 IS NULL AND (LTRIM(RTRIM(@PhoneNumber))<>'' AND @PhoneNumber IS NOT NULL)
			BEGIN
				EXEC DBO.pInsertPhone @PersonID,@PhoneNumber, @PhoneExtension,@PhoneTypeID,@ModifiedBy,@NewPhoneID output, @Succ output, @ErrorMsg output ;
			
			  IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc InsertPhone fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1);
				END
				
			
			END
		ELSE IF @PhoneID1 >0
		  BEGIN
			SELECT @CheckPhoneID = PhoneID	
				From Person.Phone
					WHERE 
						PhoneID = @PhoneID1
			 IF @CheckPhoneID = 0 OR @CheckPhoneID IS NULL --Something is wrong! Bail!
					  BEGIN
						SET @Success =0;
						SET @ErrorStatus = '-8008 Invalid PhoneID update failed';
						RAISERROR(@ErrorStatus,16,1);
					  END
						
			BEGIN
				EXEC DBO.pUpdatePhone @PhoneID1,@PersonID,@PhoneNumber, @PhoneExtension,@PhoneTypeID,@ModifiedBy,@Succ output, @ErrorMsg output;
			END
			
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc updatephone fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1);
				END
		 END
	--One more time for second phone
	SET @CheckPhoneID =0;--Reset to use again
	IF @PhoneID2 = 0 OR @PhoneID2 IS NULL AND (LTRIM(RTRIM(@PhoneNumber2))<>'' AND @PhoneNumber2 IS NOT NULL)
			BEGIN
				EXEC DBO.pInsertPhone @PersonID,@PhoneNumber2, @PhoneExtension2,@PhoneTypeID2,@ModifiedBy,@NewPhoneID2 output, @Succ output, @ErrorMsg output ;
			
			  IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc InsertPhone fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1);
				END
						
			END
		ELSE IF @PhoneID2 >0
		  BEGIN
			SELECT @CheckPhoneID = PhoneID	
				From Person.Phone
					WHERE 
						PhoneID = @PhoneID2
			 IF @CheckPhoneID = 0 OR @CheckPhoneID IS NULL --Something is wrong! Bail!
					  BEGIN
						SET @Success =0;
						SET @ErrorStatus = '-8008 Invalid PhoneID update failed';
						RAISERROR(@ErrorStatus,16,1);
					  END
						
			BEGIN
				EXEC DBO.pUpdatePhone @PhoneID2,@PersonID,@PhoneNumber2, @PhoneExtension2,@PhoneTypeID2,@ModifiedBy,@Succ output, @ErrorMsg output;
			END
			
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-13200 Sub proc updatephone fail' + @ErrorMsg;
					RAISERROR(@ErrorStatus, 16,1);
				END
		 END	 

	
	--Update Demographics... Everyone needs demographics in the basic record, so no problems here with inserts.
	BEGIN
		SELECT @CheckDemographicsID = DemographicsID	
			FROM Person.Demographics
				WHERE
					DemographicsID = @DemographicsID
				IF @DemographicsID = 0 OR @DemographicsID IS NULL --Something is wrong! Bail!
					  BEGIN
						SET @Success =0;
						SET @ErrorStatus = '-2021 Invalid DemographicsID update failed';
						RAISERROR(@ErrorStatus,16,1);
				 END
		EXEC dbo.pUpdateDemographics @DemographicsID, @PersonID,@EducationCategoryID ,@HousingStatus,@NumberInHousehold,@Gender,@Race,@CountryOfOrigin,@Ethnicity,@Disability,@CSFP,@Veteran,@HealthInsurance,@InsuranceType,@FamilyStatusType,@FoodStamps,@HomeboundDelivery,@ModifiedBy,@Succ OUTPUT, @ErrorMsg OUTPUT; 
		
		IF @Succ = 0
			BEGIN
				SET @Success =0;
				SELECT @ErrorStatus = '-2021 sub proc Update Demographics fail' + @ErrorMsg;
				RAISERROR(@ErrorStatus,16,1);
				
			END
		END
	--Check Income Source, If we find that this source  is any value, including zero we update. This will have to be modified in the future
	--to cope with multiple values on input. Question, If someone has multiple income sources on one visit and then selects only 1 on the next, does that mean that the others are gone?
		IF @IncomeSourceID <>0
			BEGIN
				UPDATE Person.Income SET 
						IncomeSourceID = @IncomeSourceID, 
						ModifiedBy = @ModifiedBy,
						ModifiedDate = SYSDATETIME()
						WHERE PersonID = @PersonID
								
			END 	
		
	--This is where we check household notes input to see if it is a new note or an update to an existing one.
		IF @HouseholdNotesID = 0 AND @IsNewNote =0 AND LTRIM(RTRIM(@Notes)) <>''--We have a problem! No such thing as an old note with 0 ID! Bail out!
			BEGIN
				SET @Success =0;
				SET @ErrorStatus ='-14008 HouseoldNoteID cant be 0 for update';
				RAISERROR(@ErrorStatus,16,1); 
			END
			
	
		IF (@IsNewNote =0 AND @HouseholdNotesID <> 0)--Update! We will assume that even a blank note is an update. Don't want to second guess the user!
			BEGIN
				EXEC dbo.pUpdateHouseholdNotes @HouseholdNotesID,@PersonID,@HouseHoldPersonID, @Notes,@ModifiedBy,@Success,@ErrorStatus;
					IF @Success =0
						BEGIN
							SET @Success =0; --redundant :)
							SET @ErrorStatus = @ErrorStatus + ' -1350 Update Client Record Failed';
							RAISERROR (@ErrorStatus,16,1);
						END 
			END
		ELSE IF LTRIM(RTRIM(@Notes)) <> '' -- Insert New Record
			BEGIN
				EXEC dbo.pInsertHouseholdNotes @PersonID,@HouseHoldPersonID,@Notes,@ModifiedBy,@NewHouseholdNotesID,@Success,@ErrorStatus;
					IF @Success =0
						BEGIN
							SET @Success =0;--Redundant
							SET @ErrorStatus = @ErrorStatus + ' -14001 Insert HouseholdNotes Failed';
							RAISERROR(@ErrorStatus,16,1);
						END
			END
			
		
		
	--This is the same as the pInsertClientRecord procedure
	--IF source is foodshelf, we need to capture whether they were in for bread/produce or groceries 
	
	IF @RecordSource ='FOOD' AND @IsUpdateBreadGroceries =1 --This is not just an update, but a foodshelf update so we make this call.
		BEGIN
			EXEC DBO.pInsertFoodTypeGiven @PersonID,@FoodReceivedDate,@FoodGiven,@ModifiedBy,@NewFoodTypeGivenID OUTPUT, @Succ OUTPUT, @ErrorMsg OUTPUT;
			IF @Succ =0
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus ='-600021 Insert FoodType fail' + @ErrorMsg;
					RAISERROR (@ErrorStatus,16,1);
				END	
	END
		

		
	--We are using nested transactions to make sure one exists in case 
	--of a rollback in subordinate Stored Procedure
	IF @@TRANCOUNT > 0 
		BEGIN
		SET @Success =1;
		SET @ErrorStatus='';
	
			COMMIT TRANSACTION;
		END

END TRY
	
BEGIN CATCH
	IF @@TRANCOUNT >0
		BEGIN
		SET @Success =0
		SET @ErrorStatus =@ErrorStatus + '  ' +@@Error
			ROLLBACK TRANSACTION;
			
		RAISERROR(@ErrorStatus,16,1);
		END
END CATCH

    
   END
    
	









GO
/****** Object:  StoredProcedure [dbo].[pUpdateContactType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUContactType
Description: Update data to LUContactType.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateContactType](
	@ContactTypeID int,
	@Name Nvarchar(50) ,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempNewContactID int
	
	SET @TempNewContactID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
				
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  
		   IF (@ContactTypeID = 0) OR (@ContactTypeID IS NULL)
			BEGIN
				SET @ErrorStatus = ' -60022 Contact Type already exists in LUContactType'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			END
		  
			SELECT @TempNewContactID = ContactTypeID 
			  FROM person.LUContactType
			     WHERE ContactTypeID = @ContactTypeID
			      
	     	IF @TempNewContactID =0 
			  BEGIN
			    SET @ErrorStatus = ' -60028 Contact Type doesnt exist in LUContactType'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			  END	
			 
          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  UPDATE Person.LUContactType
			     SET  Name = @Name,
					  ModifiedDate = SYSDATETIME(),
					  ModifiedBy = @ModifiedBy
				 WHERE ContactTypeID = @ContactTypeID
				
								
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60021 Update Failed on LUContactType';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pUpdateCountryOfOrigin]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUCountryOfOrigin
Description: Updates data to LUCountryOfOrigin.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateCountryOfOrigin](
	@CountryID int,
	@CountryAbbreviation Nvarchar(30) ='',
	@CountryName Nvarchar(50),
	@FIPSCode NVarchar(2)='',
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempNewCountryID int
	
	SET @TempNewCountryID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

	 
		
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		   IF (@CountryID = 0) OR (@CountryID IS NULL)
			 BEGIN
				SET @ErrorStatus = ' -60035 CountryID Cant be 0/NULL'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			 END
		  
		    SELECT @TempNewCountryID = CountryID 
			  FROM person.LUCountryOfOrigin
				 WHERE CountryID = @CountryID
				 
	     	IF @TempNewCountryID =0 
				BEGIN
					SET @ErrorStatus = ' -60038 Country doesnt exists in LUCountryOfOrigin'; 
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
							
				END	
 
/****************************************************************************/	          

					IF @@Error <> 0 
						BEGIN
							SELECT @ErrorStatus = @@ERROR + '-60030';
							SET @Success = 0;
							RAISERROR(@ErrorStatus, 16,1);
						END
						
				 UPDATE Person.LUCountryOfOrigin
					SET CountryAbbreviation = @CountryAbbreviation,
						CountryName = @CountryName,
						FIPSCode = @FIPSCode,
						ModifiedDate = SYSDATETIME(),
						ModifiedBy = @ModifiedBy
					WHERE CountryID = @CountryID
					
					
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			   --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60031 Update Failed Rollback';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		END












GO
/****** Object:  StoredProcedure [dbo].[pUpdateCounty]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUCounty
Description: UPdates data to LUCounty. 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateCounty](
	@CountyID int,
	@CountyName NVarchar(20),
	@StateID int,
	@CityID int = 0,--Default cityID to 0 just in case it comes in later. 
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempCountyID int
	
	SET @TempCountyID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
		
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  --The county must be tied to a state so we need to have non 0's and non-nulls in both. If one
		  --is found and not the other, it is an orphaned record. This error could be made more granular
		  --in the future, if we are concerned with orphaned records.
		  IF ((@CountyID = 0) or (@CountyID  IS NULL)) OR ((@StateID = 0) OR (@StateID IS NULL)) 
			
				BEGIN
					SELECT @ErrorStatus = '-60065 StateID/CountyID cant be NULL or 0';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
	
/****************************************************************************/
				--Check to see if the number passed in is really in the table
				SELECT @TempCountyID = CountyID 
				  FROM person.LUCounty
					 WHERE CountyID = @CountyID and StateID = @StateID
	     				If (@TempCountyID =0) OR (@TempCountyID IS NULL) 
							BEGIN
								SET @ErrorStatus = ' -60068 County Does not exist LUCounty'; 
									RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
							END	

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

				IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60060';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
				 
			  UPDATE Person.LUCounty
				  SET CityID = @CityID,
					  CountyName = @CountyName, 
					  ModifiedDate = SYSDATETIME(),
					  ModifiedBy = @ModifiedBy
					
				
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY
	

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60061 Update Failed LUCounty ';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
	END
		
	












GO
/****** Object:  StoredProcedure [dbo].[pUpdateDemographics]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO















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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Demographics
Description: Updates data to Demographics table
Revisions: 1 Nov 10. Modified to include housing status as nvarchar(50)
			1 April 11. Added @InsuranceType and @FamilyStatusType
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pUpdateDemographics](
	@DemographicsID int,
	@PersonID int,
	@EducationCategoryID int,
	@HousingStatus NVarchar(50) = NULL,
	@NumberInHousehold int,
	@Gender NVarchar(2) = NULL,
	@Race Nvarchar(20) = NULL,
	@CountryOfOrigin NVarchar(70) =NULL,
	@Ethnicity Nvarchar(20) = Null,
	@Disability NoYesMaybe =0,
	@CSFP NoYesMaybe = 0,
	@Veteran NoYesMaybe=0,
	@HealthInsurance NoYesMaybe =0 ,
	@InsuranceType NVarchar(50),
	@FamilyStatusType Nvarchar(50),
	@FoodStamps NoYesMaybe =0,
	@HomeboundDelivery NoYesMaybe =0,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempDemographicsID int,
	@TempPersonID int
	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempDemographicsID =0;		

	
		
	
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION;
				IF ((@DemographicsID = 0) OR (@DemographicsID IS NULL)) OR  ((@PersonID = 0) OR (@PersonID IS NULL))
				  BEGIN
					SELECT @ErrorStatus = '2005 DemographicsID/PersonID cant be 0/NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				  END
				
				--Check to see that the IDs match.. paranoid? NO! Have had worse things happen....Data integrity can fail!
				--Could use count but that has some optimization and indexing problems....
				SELECT @TempPersonID = PersonID, @TempDemographicsID = DemographicsID 
				  FROM person.Demographics
					 WHERE PersonID = @PersonID AND DemographicsID = @DemographicsID
			
								 
				IF ((@TempDemographicsID=0) OR (@TempDemographicsID IS NULL)) OR ((@TempPersonID =0) OR (@TempPersonID IS NULL)) 
				    BEGIN
						SELECT @ErrorStatus = ' -2008 DemographicsID/PersonID combo does not exist';
						SET @Success =0;
						RAISERROR(@ErrorStatus,16,1);
				    END

				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -2000';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END

				  UPDATE Person.Demographics
					 SET EducationCategoryID = @EducationCategoryID,
						 NumberInHousehold = @NumberInHousehold,
						 Gender = @Gender,
						 Race = @Race,
						 CountryOfOrigin = @CountryOfOrigin,
						 HousingStatus = @HousingStatus,
						 Ethnicity = @Ethnicity,
						 Disability = @Disability,
						 CSFP = @CSFP,
						 Veteran = @Veteran,
						 HealthInsurance = @HealthInsurance,
						 FamilyStatusType = @FamilyStatusType,
						 InsuranceType = @InsuranceType,
						 FoodStamps = @FoodStamps,
						 HomeboundDelivery = @HomeboundDelivery,
						 ModifiedDate = SYSDATETIME(),
						 ModifiedBy = @ModifiedBy
					 WHERE DemographicsID = @DemographicsID AND PersonID = @PersonID	
										
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-2001 Update Fail Demographics';
			  RAISERROR(@ErrorStatus, 15, 1);
			 
			  
		END CATCH
		
	END
















GO
/****** Object:  StoredProcedure [dbo].[pUpdateEthnicity]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUEthnicity
Description: Update data to LUEthnicity. 
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pUpdateEthnicity](
	@EthnicityID int,
	@EthnicityAbbreviation NVarchar(10),
	@EthnicityDescription NVarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempEthnicityID int
	
	SET @TempEthnicityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
/****************************************************************************/

	
		
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
			IF (@EthnicityID = 0) OR (@EthnicityID IS NULL)
				BEGIN
					SET @ErrorStatus = ' -60065 EthnicityID Cant be 0/NULL'; 
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
				END 
				
				SELECT @TempEthnicityID = EthnicityID 
				  FROM person.LUEthnicity
					 WHERE EthnicityID =@EthnicityID 
					 
				If @TempEthnicityID =0 --Double check to see if ID exists in db.
					BEGIN
						SET @ErrorStatus = ' -60082 Ethnicity already exists'; --Failed in lookup table
						RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
						
					END	

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

				IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60080';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
				 
			 UPDATE Person.LUEthnicity
				SET EthnicityAbbreviation = @EthnicityAbbreviation,
					EthnicityDescription = @EthnicityDescription,
					ModifiedDate = SYSDATETIME(),
					ModifiedBy = @ModifiedBy
				WHERE
					EthnicityID= @EthnicityID
					
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			    --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-60081 Update Failed Ethnicity';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateFamilyRelationship]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: FamilyRelationships
Description: Updates data to FamilyRelationships. Do not confuse with the sp that inserts to the
family relationship LU table! This stored procedure is not called directly and its superior sps do the validation, so it is left out
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateFamilyRelationship](
	@FamilyRelationshipID int,
	@PersonID int, 
	@ClientPersonID int ,
	@RelationshipID int,
	@RelationshipDescription nVarchar(50)='',
	@ModifiedBy Name, 
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempFamilyRelationshipID int
	
	SET @TempFamilyRelationshipID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/
--This stored procedure is not called directly and its superior sps do the validation, so it is left out
	
	BEGIN TRY
	  BEGIN TRANSACTION;
		
		IF @FamilyRelationshipID = 0 OR @FamilyRelationshipID IS NULL
		  BEGIN
			SELECT @ErrorStatus =  '-17501 FamilyRelationshipID cant be 0/NULL';
			SET @Success = 0;
			RAISERROR(@ErrorStatus, 16,1);
		  END
 
		IF @PersonID =0 OR @PersonID IS NULL
	      BEGIN
			SELECT @ErrorStatus =  '-17503 PersonID cant be 0/NULL';
			SET @Success = 0;
			RAISERROR(@ErrorStatus, 16,1);
	      END
	      
	     IF @ClientPersonID =0 OR @ClientPersonID IS NULL 
		   BEGIN
			SELECT @ErrorStatus =  '-17500 PersonID cant be 0/NULL';
			SET @Success = 0;
			RAISERROR(@ErrorStatus, 16,1);
	       END
		
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-17540 Update Failed';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
		
	
			BEGIN
		
				UPDATE Person.FamilyRelationships
					SET RelationshipID = @RelationshipID,
						RelationDescription =@RelationshipDescription,
						ModifiedDate = SYSDATETIME(),
						ModifiedBy = @ModifiedBy
					WHERE FamilyRelationshipID = @FamilyRelationshipID;
					
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-17540 Update Failed';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
			
				
				SET @Success =1;
				SET @ErrorStatus =0;
				COMMIT TRANSACTION;
			END
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus  +'-18001 Update Failed on FamilyRelationships';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END












GO
/****** Object:  StoredProcedure [dbo].[pUpdateFamilyStatusType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 15 March 11
*Table Name: LUFamilySTatusType
Description: Update data to LUFamilySTatusType.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateFamilyStatusType](
	@FamilyStatusTypeID int,
	@FamilySTatusType Nvarchar(50) ,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempNewFamilyStatusTypeID int
	
	SET @TempNewFamilyStatusTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
				
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  
		   IF (@FamilyStatusTypeID = 0) OR (@FamilyStatusTypeID IS NULL)
			BEGIN
				SET @ErrorStatus = ' -60022 FamilyStatusType already exists in LUFamilyStatusType'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			END
		  
			SELECT @TempNewFamilyStatusTypeID = FamilyStatusTypeID 
			  FROM person.LUFamilyStatusType
			     WHERE FamilyStatusTypeID = FamilyStatusTypeID
			      
	     	IF @TempNewFamilyStatusTypeID =0 
			  BEGIN
			    SET @ErrorStatus = ' -60028 FamilyStatusType doesnt exist in LUFamilyStatusType'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			  END	
			 
          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  UPDATE Person.LUFamilyStatusType
			     SET FamilyStatusType = @FamilyStatusType,
					  ModifiedDate = SYSDATETIME(),
					  ModifiedBy = @ModifiedBy
				 WHERE FamilyStatusTypeID = @FamilyStatusTypeID
				
								
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60021 Update Failed on LUFamilyStatusType';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateFoodTypeGiven]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: FoodTypeGiven
Description: Update data to FoodTypeGiven. This SP requires PersonID, to be valid on input
in order to capture the appropriate information. ReceivedDate should also be a valid date/time since we need to be able
to return up to 90 days history for each client in reports. This date is not tested since we have to assume
that the record may have been input on paper for some reason, so we cannot use system date to test validity.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateFoodTypeGiven](
	@FoodTypeGivenID int,
	@PersonID int ,
	@ReceivedDate DateTime,
	@FoodGiven FoodShelf.GroceryOrBreadProduce,
	@ModifiedBy Name,
	@NewFoodTypeGivenID int Output,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempFoodTypeGivenID int

	
	SET @TempFoodTypeGivenID =0;
			
	SET @Success = 0;
	SET @ErrorStatus ='';
/****************************************************************************/

	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  --Make sure that we do not have bad data
		  IF ((@FoodTypeGivenID=0) OR (@FoodTypeGivenID IS NULL)) OR((@PersonID = 0) OR (@PersonID IS NULL))
			BEGIN
				SELECT @ErrorStatus = ' -600011 @FoodTypeGivenID/PersonID/ProgramID/ServiceId not valid';
				SET @Success = 0;
				RAISERROR(@ErrorStatus,16,1);
			END
		  
		  --We now have a valid range for each ID, but need to be sure that they exist in the database before trying the Update. 
			SELECT @TempFoodTypeGivenID =  FoodTypeGivenID
			  FROM Foodshelf.FoodTypeGiven
			     WHERE  FoodTypeGivenID = @FoodTypeGivenID AND PersonID = @PersonID 
	     		  --The above could use just @FoodTypeGiven in the WHERE clause, but this is just more validation.	
	     			IF @TempFoodTypeGivenID =0 
				    	BEGIN
					     	SET @ErrorStatus = ' -600008 Record does not exist'; 
							RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
								
						END	
			 
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-600010';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			UPDATE Foodshelf.FoodTypeGiven
			   SET PersonID = @PersonID,
				   ReceivedDate = @ReceivedDate,
				   FoodGiven = @FoodGiven,
				   ModifiedDate = SYSDATETIME(),
				   ModifiedBy = @ModifiedBy
				WHERE FoodTypeGivenID = @FoodTypeGivenID
				   
					
				SET @success =1;
				SET @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-600011 Insert Failed on FoodTypeGiven';
			  RAISERROR(@ErrorStatus, 16, 1);
		
		END CATCH
	END
END


GO
/****** Object:  StoredProcedure [dbo].[pUpdateHouseholdNotes]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO













/*************************************************************************************************
*Author: Gary Savard
*Date: 2 NOV 10
*Table Name: FoodShelf.Household Notes
Description: Updates data to FoodShelf.HouseHoldNotes table.This table is for the notes associated with the
food shelf intake screens. There are 3 ID fields, the HouseholdNotesID is the identity. ClientPersonID
is the PersonID of the individual on which the note was written. The HouseholdMemberPersonID is optional, and
If this person is not the client, but a household member, this value will be the Client's personID. We 
may not need this field, but it is added for potential future functionality
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateHouseholdNotes](
	@HouseholdNotesID int,
	@ClientPersonID int,
	@HouseholdMemberPersonID int,
	@Notes Nvarchar(MAX),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempHouseholdNotesID int,
	@TempClientPersonID int,
	@TempHouseholdMemberPersonID int
	
	SET @TempHouseholdNotesID =0;
	SET @TempClientPersonID = 0;	
	SET @Success = 0;
	SET @ErrorStatus ='';
	



		BEGIN TRY
		  BEGIN TRANSACTION;
				/****************************************************************************/
			--Validate  IDs coming in. Only the HouseholdNotesID and ClientPersonID are mandatory, 
			
			SELECT @TempHouseholdNotesID = @HouseholdNotesID
				FROM Foodshelf.HouseholdNotes	
					WHERE HouseholdNotesID = @HouseholdNotesID
			
			IF @TempHouseholdNotesID = 0 OR @TempHouseholdNotesID IS NULL
				BEGIN
					SET @ErrorStatus ='-14008 Record does not exist';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1); 
				END		
			
			SELECT @TempClientPersonID = PersonID 
			  FROM person.Person
				 WHERE PersonID = @ClientPersonID
			
			If @TempClientPersonID = 0 or @TempClientPersonID IS NULL
			BEGIN
				SET @ErrorStatus = ' -14008 ClientPersonID does not exist in Person'; --Failed in person table
				SET @Success =0;
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
				
			END	
		
		--Since this is an optional field, we only check it if it has a value other than 0 or NULL	
		IF @HouseholdMemberPersonID <> 0 AND @HouseholdMemberPersonID IS NOT NULL	
		 BEGIN
			SELECT @TempHouseholdMemberPersonID = @HouseholdMemberPersonID
				FROM Person.Person
					WHERE PersonID = @HouseholdMemberPersonID
		
			IF @TempHouseholdMemberPersonID = 0 OR @TempHouseholdMemberPersonID IS NULL
				BEGIN
					SET @ErrorStatus =' -14016 HouseholdMemberPersonID does not exist, though not NULL/0';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END			
		END
		/****************************************************************************/	          

			
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-14000';
				SET @Success = 0;
				RAISERROR (@ErrorStatus,16,1);
			END
			
			  UPDATE Foodshelf.HouseholdNotes 
				 SET ClientPersonID = @ClientPersonID, 
					 HouseholdMemberPersonID = @HouseholdMemberPersonID, 
					 Notes = @Notes,
					 ModifiedBy = @ModifiedBy, 
					 ModifiedDate = SYSDATETIME()
				 WHERE HouseholdNotesID = @HouseholdNotesID  --Don't bother with other Ids here since this is the identity for the row.
				
				
				SET @success =1;
				SET @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			 --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
			 
			 SELECT @ErrorStatus =@ErrorStatus + ' -14000' +' Update Failed HouseholdNotes';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END













GO
/****** Object:  StoredProcedure [dbo].[pUpdateHousingStatus]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUHousingStatus
Description: Updates data to LUHousingStatus. 
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateHousingStatus](
	@HousingStatusID int,
	@HousingStatus NVarchar(20),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempHousingStatusID int
	
	SET @TempHousingStatusID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

	 
	BEGIN TRY
		BEGIN TRANSACTION;
			/****************************************************************************/

			SELECT @TempHousingStatusID = HousingStatusID 
			  FROM person.LUHousingStatus
				 WHERE HousingStatusID = @HousingStatusID
				 
			If (@TempHousingStatusID =0) OR (@TempHousingStatusID IS NULL) 
				BEGIN
					SET @ErrorStatus = ' -60098 Does not exist in LUHousingStatus'; --Failed in lookup table
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
					
				END	

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

				IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
			
				BEGIN
		
		 			UPDATE Person.LUHousingStatus
		 				SET HousingStatus = @HousingStatus,
		 					ModifiedDate = SYSDATETIME(),
		 					ModifiedBy = @ModifiedBy
						WHERE
							HousingStatusID = @HousingStatusID
				
					
					set @success =1;
					set @ErrorStatus =0;
					COMMIT TRANSACTION;
				END
		
	
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + +'-60021 Insert Failed Housing Status';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
END









GO
/****** Object:  StoredProcedure [dbo].[pUpdateIncomeSource]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO











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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Address
Description: Update data to LUIncomeSource table.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateIncomeSource](
	@IncomeSourceID int,
	@IncomeSourceAbbreviation NVarchar(10),
	@IncomeSourceDescription Nvarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempIncomeSourceID int
	
	SET @TempIncomeSourceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
		


	
	BEGIN TRY
			BEGIN TRANSACTION;
			/****************************************************************************/
	
		--the address, so we need to be sure that the data matches an address type before continuing.
	SELECT @TempIncomeSourceID = IncomeSourceID 
	  FROM person.LUIncomeSource
		 WHERE IncomeSourceID = @IncomeSourceID 
			
				IF (@IncomeSourceID = 0) OR (@IncomeSourceID IS NULL)
				  BEGIN
				    SET @ErrorStatus = ' -6095 Income Source exists in LUIncomeSource'; --Failed in lookup table
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
				END
			
				IF @TempIncomeSourceID = 0
				   BEGIN
					 SET @ErrorStatus = ' -6098 Income Source  doesnt exist LUIncomeSource'; --Failed in lookup table
					 RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
					
				END	 
/****************************************************************************/	          

				IF @@Error <> 0 
				   BEGIN
						SELECT @ErrorStatus = @@ERROR + '-6090';
						SET @Success = 0;
						RAISERROR (@ErrorStatus,16,1);
				    END
	 
		
		
			  UPDATE Person.LUIncomeSource
				 SET IncomeSourceAbbreviation = @IncomeSourceAbbreviation,
				     IncomeSourceDescription = @IncomeSourceDescription,
				     ModifiedDate = SYSDATETIME(), 
				     ModifiedBy = @ModifiedBy
					
				
					set @success =1;
					set @ErrorStatus =0;
				COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
				--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			 SELECT @ErrorStatus =@ErrorStatus + ' -6091' +' Update Failed LUIncomeSource';
			 SET @Success =0;
			 
			 RAISERROR(@ErrorStatus, 16, 1);
			 	 
		
		END CATCH
		
	
END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateInsuranceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 15 March 11
*Table Name: LUInsuranceType
Description: Update data to LUInsuranceType.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateInsuranceType](
	@InsuranceTypeID int,
	@InsuranceType Nvarchar(50) ,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempNewInsuranceTypeID int
	
	SET @TempNewInsuranceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
				
	
	BEGIN
		BEGIN TRY
		  BEGIN TRANSACTION;
		  
		   IF (@InsuranceTypeID = 0) OR (@InsuranceTypeID IS NULL)
			BEGIN
				SET @ErrorStatus = ' -60022 Insurance Type already exists in LUInsuranceType'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			END
		  
			SELECT @TempNewInsuranceTypeID = InsuranceTypeID 
			  FROM person.LUInsuranceType
			     WHERE InsuranceTypeID = @InsuranceTypeID
			      
	     	IF @TempNewInsuranceTypeID =0 
			  BEGIN
			    SET @ErrorStatus = ' -60028 Insurance Type doesnt exist in LUInsuranceType'; 
				RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
			  END	
			 
          

	IF @@Error <> 0 
	BEGIN
		SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-60020';
		SET @Success = 0;
		RAISERROR(@ErrorStatus, 16,1);
	END
	 
			  UPDATE Person.LUInsuranceType
			     SET  InsuranceType = @InsuranceType,
					  ModifiedDate = SYSDATETIME(),
					  ModifiedBy = @ModifiedBy
				 WHERE InsuranceTypeID = @InsuranceTypeID
				
								
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus + '-60021 Update Failed on LUInsuranceType';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateLanguage]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
*Author: Gary Savard
*Date: 15 Oct 10
*Table Name: LULanguage
Description: Updates data to LULangage. This table Contains the most common languages and dialects in the world.Dialects
are comma demlmited. Example: Chinese, Mandarin.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateLanguage](
	@LanguageID int,
	@LanguageName Nvarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempLanguageID int
	
	SET @TempLanguageID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		BEGIN TRY
		  BEGIN TRANSACTION;
		  /****************************************************************************/
			--Double check to see that we do have a correct languageID before trying to update
			SELECT @TempLanguageID = LanguageID 
				FROM person.LULanguage
				WHERE LanguageID = @LanguageID

		  /****************************************************************************/	          
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '  -6060';
					SET @Success = 0;
					RAISERROR(@ErrorStatus,16,1);
				END
			 IF (@TempLanguageID = 0) or (@TempLanguageID IS NULL)
				BEGIN
					SELECT @ErrorStatus = '-6068 Language does not exist in db';
					SET @Success =0;
					RAISERROR(@ErrorStatus, 16,1);
				END
				
				IF @TempLanguageID <> 0 --Don't really need this, but... it exists in the database then
					BEGIN
					
						UPDATE Person.LULanguage
							SET LanguageName = @LanguageName,
								ModifiedDate = SYSDATETIME(),
								ModifiedBy = @ModifiedBy
							WHERE
								LanguageID = @LanguageID
								
							
								set @success =1;
								set @ErrorStatus =0;
						COMMIT TRANSACTION;
					END		
				
			END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT  @ErrorStatus= @ErrorStatus + 'LULanguage-6061';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateLUFamilyRelationships]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUFamilyRelationships
Description: Updates data to LUFamilyRelationships.
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateLUFamilyRelationships](
	@FamilyRelationshipID int, 
	@RelationshipCode Nvarchar(30),
	@RelationshipDescription Nvarchar(50) ='',
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempFamilyRelationshipID int
	
	SET @TempFamilyRelationshipID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	
/****************************************************************************/

	
	BEGIN TRY
		 BEGIN TRANSACTION;
			IF (@FamilyRelationshipID =0) OR (@FamilyRelationshipID IS NULL)
				BEGIN
					SELECT @ErrorStatus = ' -60045 FamilyRelationshipID cant be 0/NULL';
					SET @Success =0;
					RAISERROR(@ErrorStatus, 16,1);
				END 
		 
		 
			SELECT @TempFamilyRelationshipID = FamilyRelationshipID 
			   FROM person.LUFamilyRelationship
			   WHERE FamilyRelationshipID = @FamilyRelationshipID 
			   
	     	If @TempFamilyRelationshipID =0 
				BEGIN
					SET @ErrorStatus = ' -60048 RelationshipID doesnt exist  LUFamilyRelationship'; 
					RAISERROR(@ErrorStatus,16,1);--Could use WITH LOG for event log
					
				END	
 
			IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = Convert(nVarchar(50),@@ERROR) + '-60040';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
		
	
		BEGIN
		
			  UPDATE Person.LUFamilyRelationship
				  SET RelationshipCode = @RelationshipCode,
					  RelationshipDescription = @RelationshipDescription,
					  ModifiedDate = SYSDATETIME(),
					  ModifiedBy = @ModifiedBy
				   WHERE FamilyRelationshipID = @FamilyRelationshipID
					
				
			
				set @success =1;
				set @ErrorStatus =0;
				COMMIT TRANSACTION;
			END
		
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus  +'-60041 Update Failed LUFamilyRelationship';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pUpdatePerson]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Person
Description: Update data to Person table
Revisions:
**************************************************************************************************/
CREATE PROCEDURE [dbo].[pUpdatePerson](
	@PersonID int,
	@Title NVarchar(8) =NULL,
	@FirstName Name,
	@MiddleName Name = Null,
	@LastName Name,
	@Suffix NVarchar(10) = Null,
	@DateOfBirth DateTime,
	@EmailAddress Nvarchar(50) = Null,
	@EmailContactPreference NoYes =0,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int

	
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	SET @TempPersonID =0;		


	           
BEGIN TRY
	 BEGIN TRANSACTION;
	 
		IF ((@PersonID = 0) OR (@PersonID IS NULL))
			BEGIN
				SELECT @ErrorStatus = 'Person ID cant be 0 or NULL -1005';
				SET @Success = 0;
				RAISERROR (@ErrorStatus,16,1);
			END
		BEGIN
			SELECT @TempPersonID = PersonID from Person.Person
				WHERE
					PersonID = @PersonID
			IF @TempPersonID =0 OR @TempPersonID IS NULL
				BEGIN
					SET @Success =0;
					SELECT @ErrorStatus = '-1008 Person does not exist';
					RAISERROR(@ErrorStatus,16,1);
				END
		END	
		
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-1000';
				SET @Success = 0;
			END
		 
			
			 UPDATE Person.Person
				SET Title = @Title,
				    FirstName = @FirstName,
					MiddleName = @MiddleName,
					LastName = @LastName,
					Suffix = @Suffix,
					DateOfBirth = @DateOfBirth, 
					EmailAddress = @EmailAddress,
					EmailContactPreference = @EmailContactPreference,
					ModifiedDate = SYSDATETIME(),
					ModifiedBy = @ModifiedBy
				WHERE PersonID = @PersonID
					
				
				
				SET @success =1;
				SET @ErrorStatus =0;
			COMMIT TRANSACTION;
	
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SET @ErrorStatus=  @ErrorStatus + 'Update Person Failed -1001';
			  RAISERROR(@ErrorStatus, 15, 1);
		
			  
		END CATCH
		
	END







GO
/****** Object:  StoredProcedure [dbo].[pUpdatePersonType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LUPersonType
Description: Updates data to LUPersonType. 
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdatePersonType](
	@PersonTypeID int,
	@PersonType NVarchar(20),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonTypeID int
	
	SET @TempPersonTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

BEGIN TRY
	BEGIN TRANSACTION;
	/****************************************************************************/
	--Does it already exist? If not, then do not try to update!
	SELECT @TempPersonTypeID = PersonTypeID  
	  FROM person.LUPersonType
	     WHERE PersonTypeID = @PersonType

/****************************************************************************/	          
		IF (@TempPersonTypeID = 0) OR (@TempPersonTypeID IS NULL)
			BEGIN
				SELECT @ErrorStatus = @@ERROR + '-600008 PersonType does not exists';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = @@ERROR + '-600000';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
		 
		
	
		BEGIN
		
			  UPDATE Person.LUPersonType
				 SET PersonType = @PersonType,
					 ModifiedDate = SYSDATETIME(),
					 ModifiedBy = @ModifiedBy
				 WHERE PersonTypeID = @PersonTypeID
					
				
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		END
END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-600001 Update Failed Person Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pUpdatePhone]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Phone
Description: Update data to phone table. The row is tied to the person.personid. This Stored proc/table does not directly
access the LUPhoneType table. The type is selected by the user from a dropdown and we just store the ID from the dropdown behind the scenes  
 for simplicity
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdatePhone](
	@PhoneID int,
	@PersonID int,
	@PhoneNumber Phone,
	@PhoneExtension NVarchar(8),
	@PhoneType int,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempPhoneID int,
	@TempPersonID int
	
	SET @TempPhoneID =0;
	SET @TempPersonID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';


    BEGIN TRY
		  BEGIN TRANSACTION;
			IF ((@PersonID = 0) OR (@PersonID IS NULL) OR (@PhoneID = 0) OR (@PhoneID IS NULL)) -- This has to be valid or we bail out!
				BEGIN
					SET @Success =0;
					SET @ErrorStatus = '-8005: PersonID/PhoneID must be valid';
						
					RAISERROR(@ErrorStatus,16,1);
				END
				
			BEGIN
				SELECT @TempPersonID = PersonID, @TempPhoneID = @PhoneID
					FROM Person.Phone
						WHERE
							PersonID =@PersonID AND @PhoneID = @PhoneID
							
				IF ((@TempPersonID = 0) OR (@TempPersonID IS NULL)) OR ((@TempPhoneID = 0) OR (@TempPhoneID IS NULL))	
					BEGIN
						SET @ErrorStatus ='-8008 PersonID or PhoneID not valid';
						SET @Success =0;
						RAISERROR (@ErrorStatus, 16, 1);
					END		
			
				IF @@Error <> 0 
					BEGIN
						SELECT @ErrorStatus = @@ERROR + '-8030';
						SET @Success = 0;
						RAISERROR(@ErrorStatus, 16, 1);
					END
			END
	 	
			 UPDATE Person.Phone
				SET PersonID = @PersonID,
					PhoneNumber = @PhoneNumber,
					PhoneExtension = @PhoneExtension,
					PhoneType = @PhoneType,
					ModifiedDate = SYSDATETIME(),
					ModifiedBy = @ModifiedBy
				WHERE PhoneID = @PhoneID
			 
					
				SET @success =1;
				SET @ErrorStatus =0;
				
		  COMMIT TRANSACTION;
			
	END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
				
	  	    SELECT @ErrorStatus= @ErrorStatus + '8001 Update Failed';
		    RAISERROR(@ErrorStatus, 16, 1);
		    SET @Success =0;
			 
			
		END CATCH

		














GO
/****** Object:  StoredProcedure [dbo].[pUpdatePhoneType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




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

*Author: Gary Savard
*Date: 12 Oct 10
*Table Name: LUPhoneType
Description: Updage Phone Type to the LUPhoneType table.The data in this table could easily become
poor if the user does not take care when inserting phone types. A mis-spelling can cause unintential duplicate
records.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdatePhoneType](
	@PhoneTypeID int,
	@PhoneType int,
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPhoneTypeID int
	
	SET @TempPhoneTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	


	
		 
BEGIN TRY
  BEGIN TRANSACTION;	
	IF (@PhoneTypeID = 0) OR (@PhoneTypeID IS NULL)
		BEGIN
			SET @ErrorStatus = '-6085' + ' PhoneTypeID Cant be 0/NULL' ; 
			 RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
		END
		
	SELECT @TempPhoneTypeID = PhoneTypeID
	  FROM person.LUPhoneType
		 WHERE PhoneTypeID = @PhoneTypeID
  	 
	
	IF @TempPhoneTypeID = 0
	BEGIN
	SET @ErrorStatus = '-6088' + ' PhoneType doesnt exists LUPhoneType' ; --Failed in lookup table
		RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
		
	END	
       

	IF @@Error <> 0 
		BEGIN
			SET @ErrorStatus = '-6080';
			SET @Success = 0;
			RAISERROR (@ErrorStatus,16,1);
		END
	   	
	  	 UPDATE Person.LUPhoneType
	  		SET PhoneType = @PhoneType,
	  			ModifiedDate= SYSDATETIME(), 
	  			ModifiedBy = @ModifiedBy
	  		WHERE PhoneTypeID = @PhoneTypeID
				
			set @success =1;
			set @ErrorStatus ='';
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
		--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			 
			  SET @ErrorStatus= @Errorstatus + ' -6081' +'Insert Failed on Phone Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			  ROLLBACK TRANSACTION;
		END CATCH
		

END








GO
/****** Object:  StoredProcedure [dbo].[pUpdatepHouseholdTransferOptions]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




/*************************************************************************************************
*Author: Gary Savard
*Date: 22 April 11
*Table Name: LUHouseholdTransferOptions
Description: Update data to LUHouseholdTransferOptions. 
Revisions:

**************************************************************************************************/
CREATE PROCEDURE [dbo].[pUpdatepHouseholdTransferOptions](
	@ActionToTakeID int,
	@ActionToTake Nvarchar(50),
	@ActionToTakeDescription NVarchar(MAX),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

BEGIN
	DECLARE
	@TempActionToTakeID int
	
	SET @TempActionToTakeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		
	

		BEGIN TRY
			BEGIN TRANSACTION;
		
			/****************************************************************************/
				
				
			SELECT @TempActionToTakeID = HouseholdTransferActionID 
			  FROM dbo.LUHouseholdTransferOptions
				 WHERE HouseholdTransferActionID = @ActionToTakeID 
				 
			If @TempActionToTakeID = 0 --Cant Update if it doesnt exist
				BEGIN
					SELECT @ErrorStatus = '-6015 Action Type Does Not Exists';
					SET @Success =0;
					RAISERROR(@ErrorStatus, 16, 1);
				END

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

			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = Convert (nVarchar(50),@@ERROR) + ' -6010';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16, 1);
				END
	 
			
			 UPDATE dbo.LUHouseholdTransferOptions
				SET ActionToTake = @ActionToTake,
					ActionToTakeDescription = @ActionToTakeDescription,
					ModifiedBy = @ModifiedBy,
					ModifiedDate = SYSDATETIME()
				WHERE 
					HouseholdTransferActionID =@ActionToTakeID;
					
			
				
				set @success =1;
				set @ErrorStatus ='';
			COMMIT TRANSACTION;
		
		END TRY

		BEGIN CATCH
			
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SET @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			   	
		
			  SET @Success =0;
			  SELECT  @ErrorStatus = @ErrorStatus + 'Update Failed Rollback -6011';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		

END









GO
/****** Object:  StoredProcedure [dbo].[pUpdatePostalCode]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








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

*Author: Gary Savard
*Date: 12 Oct 10
*Table Name: LUPostalCode
Description: Inserts Postal Code to the Postal Code table.This requires that the CityID be passed in as a
paramter. It is unlikely that a new city will be build, requiring a new postal code, but it is very likely
that a new postal code will be needed in a city.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdatePostalCode](
	@PostalCodeID int,
	@CityID int,
	@PostalCode Nvarchar(10),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempCityID int,
	@TempPostalCodeID int
	
	SET @TempPostalCodeID = 0;
	SET @TempCityID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	


	
		
BEGIN TRY
	BEGIN TRANSACTION;	 
	
	IF ((@TempPostalCodeID = 0)OR (@TempPostalCodeID IS NULL)) AND ((@TempCityID =0) OR (@TempCityID IS NULL)) 
		BEGIN
			SET @ErrorStatus = '-6075' + ' PostalCodeId/CityID cant be 0/NULL' ;
			RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
		END
	
	/****************************************************************************/
	--Check to be sure that the city ID and PostalCode ID does exist in the city table before we go on. We could
	--just use postal code ,but adding CityID allows for updates to mistakes in city when entered.
		
	
	SELECT @TempCityID = CityID
	  FROM person.LUCity
		 WHERE CityID = @CityID
		
	SELECT @TempPostalCodeID = PostalCodeID
	  FROM Person.LUPostalCode
		WHERE PostalCodeID = @PostalCodeID
	
	If @TempCityID = 0 OR @TempPostalCodeID = 0
		BEGIN
			SET @ErrorStatus = '-6072' + ' CityID or PostalCodeID doesnt exist in LUtables, cant Update PostalCode' ; --Failed in lookup table
			RAISERROR(@ErrorStatus,15,1);--Could use WITH LOG for event log
			
		END	
/****************************************************************************/	          

	IF @@Error <> 0 
	BEGIN
		SET @ErrorStatus = '-6070';
		SET @Success = 0;
		RAISERROR (@ErrorStatus,16,1);
	END
	 
		
		  UPDATE Person.LUPostalCode
			 SET CityID =@CityID,--Do this in case there was a mistake in original insert
				 PostalCode = @PostalCode,
				 ModifiedDate = SYSDATETIME(),
				 ModifiedBy = @ModifiedBy
			 WHERE PostalCodeID = @PostalCodeID
				
				
				set @success =1;
				set @ErrorStatus ='';
				COMMIT TRANSACTION;
		
END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION;
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SET @ErrorStatus='-6071' +'Update Failed on PostalCode';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			  
		END CATCH
		

END








GO
/****** Object:  StoredProcedure [dbo].[pUpdateProgramServiceType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUprogramServiceType
Description: Update data to LUProgramServiceType. This table matches the Program with the service being
used by the client.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateProgramServiceType](
	@ProgramServiceTypeID int,
	@ServiceCode Nvarchar(20),
	@ServiceDescription NVarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;

	DECLARE
	@TempProgramServiceTypeID int
	
	SET @TempProgramServiceTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
BEGIN        
  BEGIN TRY
	  BEGIN TRANSACTION;
		IF ((@ProgramServiceTypeID = 0) OR (@ProgramServiceTypeID IS NULL))
			BEGIN
				SELECT @ErrorStatus = '-6055 ProgramServiceTypeID cant be 0 or NULL';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16,1);
			END
			
		SELECT @TempProgramServiceTypeID = ProgramServiceTypeID
				FROM Person.LUProgramServiceType
				WHERE ProgramServiceTypeID = @ProgramServiceTypeID	
				
		IF (@TempProgramServiceTypeID = 0) OR (@TempProgramServiceTypeID IS NULL) 
				BEGIN
					SELECT @ErrorStatus = '-6058 ProgramServiceTypeID cant be 0 or NULL';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END

			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + ' -6040';
					SET @Success = 0;
					RAISERROR(@ErrorStatus, 16,1);
				END
		 
		
	
	  BEGIN
		
			  UPDATE Person.LUProgramServiceType
				 SET ServiceCode = @ServiceCode,
					 ServiceDescription = @ServiceDescription,
					 ModifiedDate = SYSDATETIME(),
					 ModifiedBy = @ModifiedBy
				 WHERE ProgramServiceTypeID = @ProgramServiceTypeID
				
				set @success =1;
				set @ErrorStatus =0;
			 COMMIT TRANSACTION;
		END
		
	END TRY

		BEGIN CATCH
			--We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus=@ErrorStatus+ 'Update failed Rollback -6051';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pUpdateProgramType]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUProgramType
Description: Update data to LUProgramType. This table matches the Program with the user.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateProgramType](
	@ProgramTypeID int,
	@ProgramName Nvarchar(20),
	@ProgramDescription NVarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempProgramTypeID int
	
	SET @TempProgramTypeID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

BEGIN TRY
	BEGIN TRANSACTION;
		IF(@ProgramTypeID = 0) OR (@ProgramTypeID IS NULL)
			BEGIN
				SELECT @ErrorStatus = '-6045 ProgramTypeID cant be 0/null';
				SET @Success =0;
				RAISERROR(@ErrorStatus,16,1);
			END
		BEGIN	
		SELECT ProgramTypeID = @ProgramTypeID
			FROM Person.LUProgramType
			  WHERE ProgramTypeID = @ProgramTypeID
		
		    IF(@ProgramTypeID = 0) OR (@ProgramTypeID IS NULL)
				BEGIN
					SELECT @ErrorStatus = '-6048 ProgramType does not exist';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END
		
		END	  	
		
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = @@ERROR + ' -6040';
				SET @Success = 0;
			END
		 
		

	  BEGIN
		
			  UPDATE Person.LUProgramType
				 SET ProgramName = @ProgramName,
					 ProgramDescription = @ProgramDescription,
					 ModifiedDate = SYSDATETIME(), 
					 ModifiedBy = @ModifiedBy
				 WHERE
					ProgramTypeID = @ProgramTypeID
					
				SET @success =1;
				SET @ErrorStatus =0;
			COMMIT TRANSACTION;
	 END	
	 
		
		END TRY

		BEGIN CATCH
		  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
			--We only care if the error was not raised by SSE
			IF @@ERROR <> 50000
				BEGIN
					SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
				END
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus= @ErrorStatus +' -6041 Update Failed on Program Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			 
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pUpdateRace]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






/*************************************************************************************************
*Author: Gary Savard
*Date: 9 Oct 10
*Table Name: LURace
Description: Update data to LURace. This table matches the Race with a U.S Census race category
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateRace](
	@RaceID int,
	@RaceAbbreviation NVarchar(10),
	@RaceDescription NVarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus NVarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempRaceID int
	
	SET @TempRaceID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	
	          
BEGIN TRY
	BEGIN TRANSACTION;
	/****************************************************************************/
	--Check to see if the RaceID Exists in the DB. Validates the Race ID Input
	--White, Black(AA or Negro).American Indian or Alaskan native.,Asian Indian,Chinese,Filipino, Other Asian, Japanese,
	--Korean, Vietnamese, Native Hawaiian, Guanamanian or Chamorro, Samoan, Other pacific Islander.
	SELECT @TempRaceID = RaceID 
	  FROM person.LURace
	     WHERE RaceID = @RaceID --Be a bit paranoid and trim the input for white spaces


/****************************************************************************/
		IF @@Error <> 0 
		BEGIN
			SELECT @ErrorStatus = @@ERROR + '-6020';
			SET @Success = 0;
			RAISERROR(@ErrorStatus, 16,1);
			
		END
		IF (@TempRaceID = NULL) or (@TempRaceID =0) -- can't update if doesnt exist
			SELECT @ErrorStatus ='-6028 Does not exist in DB';
			SET @Success = 0;
			RAISERROR (@ErrorStatus,16,1);
			 
		 
		
	IF @TempRaceID <> 0 --If they exist in the database then
		BEGIN
		
			  UPDATE Person.LURace
			  SET RaceAbbreviation = @RaceAbbreviation,
				  RaceDescription = @RaceDescription,
				  ModifiedDate = SYSDATETIME(),
				  ModifiedBy =@ModifiedBy
			  WHERE
				  RaceID = @RaceID;
			  			
				set @success =1;
				set @ErrorStatus =0;
			COMMIT TRANSACTION;
		END
END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT @ErrorStatus= @ErrorStatus +'-6021 Update Failed Race Type';
			  RAISERROR(@ErrorStatus, 16, 1);
			
			
		END CATCH
		
	END










GO
/****** Object:  StoredProcedure [dbo].[pUpdateSSN]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










/*************************************************************************************************
*Author: Gary Savard
*Date: 15 Oct 10
*Table Name: SSN.SSN
Description: Updates data to SSN. Only Certain federal programs require that SSN be captured, so we only want to
use this sparingly.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateSSN](
	@SSNID int,
	@PersonID int,
	@SSN NVarchar(9),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempPersonID int,
	@TempSSNID int
	
	SET @TempPersonID =0;
	SET @TempSSNID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

		BEGIN TRY
		  BEGIN TRANSACTION;
		  SELECT @SSN = ltrim(rtrim(@SSN)); --Get rid of spaces before we begin!
		  /****************************************************************************/
			IF ((@PersonID = 0) OR (@PersonID IS NULL)) 
				BEGIN	
					SELECT @ErrorStatus = '-12005 PersonID cant be 0/NULL';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1); 
					
				END
			IF ((LEN(@SSN)<9) OR (@SSN IS NULL))
				BEGIN	
					SELECT @ErrorStatus = '-11006 Invalid SSN Null or <9 Characters';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1); 
				
				END
			
			IF (@SSNID = 0 OR @SSNID IS NULL)
				BEGIN
					SELECT @ErrorStatus ='-12006 SSNID Cant be 0/NULL';
					SET @Success =0;
					RAISERROR (@ErrorStatus,16,1);
				END
		

			--Final check to be sure this is not a duplicate
			
			SELECT @TempSSNID = SSNID 
				FROM SSN.SSN
					WHERE PersonID = @PersonID AND SSNID =@SSNID
								
			IF @TempSSNID = 0 
				--No Record, Cant update! 
				BEGIN
					SELECT @ErrorStatus = '-12008 Record Does not Exist';
					SET @Success =0;
					RAISERROR(@ErrorStatus,16,1);
				END
				


			/****************************************************************************/	          
			IF @@Error <> 0 
				BEGIN
					SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '  -12001';
					SET @Success = 0;
					RAISERROR(@ErrorStatus,16,1);
				END
			 
				
				
				
					
						UPDATE SSN.SSN 
						    SET PersonID = @PersonID,
								SSN = @SSN,
								ModifiedDate = SYSDATETIME(),
							    ModifiedBy = @ModifiedBy
								 
							WHERE SSNID = @SSNID
								
							
								SET @success =1;
								SET @ErrorStatus =0;
								
						COMMIT TRANSACTION;
						
				
			END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SET @Success =0;
			  SELECT  @ErrorStatus= @ErrorStatus + 'SSN -12001';
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[pUpdateState]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: LUState
Description: Update data to LUState. This table matches the State with a State ID for ties to County, City and Zip Code.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [dbo].[pUpdateState](
	@StateID int,
	@StateCode Nvarchar(2),
	@Name Nvarchar(50),
	@ModifiedBy Name,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE
	@TempStateID int
	
	SET @TempStateID =0;
	SET @Success = 0;
	SET @ErrorStatus ='';
	

BEGIN TRY
	 BEGIN TRANSACTION;
	 /****************************************************************************/
--This could go after the test for @StateId =0 but will leave here
	SELECT @TempStateID = StateID 
	  FROM person.LUState
	     WHERE StateID = @StateID

/****************************************************************************/	          
		IF (@TempStateId = NULL) OR (@TempStateID = 0)
			BEGIN
				SELECT @ErrorStatus = 'State does not exist -6038';
				SET @Success =0;
				RAISERROR(@ErrorStatus, 16,1);
			END
			
		IF @@Error <> 0 
			BEGIN
				SELECT @ErrorStatus = CONVERT(nVarchar(50),@@ERROR) + '-6030';
				SET @Success = 0;
				RAISERROR(@ErrorStatus, 16, 1);
			END
		
			
		IF @StateID = 0
			BEGIN
				SELECT @ErrorStatus = '@StateID cant be 0 -6035';
				SET @Success =0;
				RAISERROR(@ErrorStatus, 16,1);
			END
	 
		
			  UPDATE Person.LUState
				SET StateCode = @StateCode,
					Name = @Name,
					ModifiedBy = @ModifiedBy,
					ModifiedDate = SYSDATETIME()
				WHERE
					StateID = @StateID;
			 
							
				set @success =1;
				set @ErrorStatus =0;
			 COMMIT TRANSACTION;
	
			
		END TRY

		BEGIN CATCH
			  ROLLBACK TRANSACTION;
			  SET @Success =0;
			  SET @ErrorStatus= @ErrorStatus + @@ERROR + '-6031 Update Failed on State';--6030-6039 is for this table
			  RAISERROR(@ErrorStatus, 16, 1);
			 
			  
		END CATCH
		
	END











GO
/****** Object:  StoredProcedure [dbo].[spInsertJournalClientFamilyChanges]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		Gary Savard
-- Create date: 6 JUNE 11
-- Description:	This sp inserts a row in the journaling table for recordkeeping of admin functions.
-- 
-- =============================================
CREATE PROCEDURE [dbo].[spInsertJournalClientFamilyChanges]
(
	@HouseholdMembersID int,
	@PreviousClientsID int,
	@NewClientsID int,
	@ActionTaken NVarchar(50),
	@Notes NVarchar(MAX),
	@ModifiedBy Name
			
)

AS
BEGIN
BEGIN TRANSACTION
--No Error handling used because we do not want to affect the main sp with problems here.
	
		INSERT dbo.JournalClientFamilyChanges 
				(HouseholdMembersID,
				PreviousClientsID,
				NewClientsID,
				ActionTaken,
				Notes,
				ModifiedBy,
				ModifiedDate)
		VALUES
				(@HouseholdMembersID,
				@PreviousClientsID,
				@NewClientsID,
				@ActionTaken,
				@Notes,
				@ModifiedBy,
				SYSDATETIME())
				
				
IF @@ROWCOUNT >0
	COMMIT TRANSACTION
ELSE
	ROLLBACK TRANSACTION
END



GO
/****** Object:  StoredProcedure [Signature].[pInsertSignature]    Script Date: 1/6/2018 9:07:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





/*************************************************************************************************
*Author: Gary Savard
*Date: 8 Oct 10
*Table Name: Signature.Signatures and Signature.Signature
Description: The signature history for each client must be kept in the signature table,thus there is an interchange
table called signatures that creates the relationship ties between the person and signature table.This procedure first
insterts to Singnature, retrieves the new SignatureID and makes the tie by inserting a row in the Signatures table. 
We do not need to do updates to this procedure since a new row must always be generated for the client.
Revisions:
**************************************************************************************************/

CREATE PROCEDURE [Signature].[pInsertSignature](
	@PersonID int,
	@Signature varChar(MAX),
	@ModifiedBy Name,
	@NewSignatureID int Output,
	@NewSignaturesID int Output,
	@Success bit Output,
	@ErrorStatus Nvarchar(50) Output
	)
AS

Set NoCount ON;


	DECLARE
	@TempSignatureID int,
	@TempPersonID int,
	@ProcedureLocation varchar,
	@TempSignaturesID int;
	
	
	SET @TempSignatureID =0;
	SET @TempPersonID =0;
	SET @TempSignaturesID =0;
	SET @Success = 0;
	SET @ProcedureLocation ='';
	SET @ErrorStatus ='';
	
	          

BEGIN TRANSACTION; --We will wrap both inserts in the same transaction to avoid orphaned data
  BEGIN TRY
  /****************************************************************************/
	--Check to see if this person already has a signaure. This is not required with the current procedure but 
	--is potentially required in the future so it remains. 	
		SELECT @TempPersonID = @PersonID
		  FROM Signature.Signature
			 WHERE Signature.PersonID = @PersonID 

/****************************************************************************/
  
	IF @@Error <> 0 
	BEGIN
		SET @ErrorStatus = @@ERROR + '-4000'; --Range for Signature/Signatures
		SET @Success = 0;
		RAISERROR (@ErrorStatus,16,1);
	END

	   BEGIN
	  				
					INSERT INTO Signature.Signature(PersonID,Signature.Signature,ModifiedDate, ModifiedBy)
						VALUES (@PersonID,@Signature,SYSDATETIME(),@ModifiedBy)
					
					SET @TempSignatureID =@@IDENTITY;
					SET @ErrorStatus =@@ERROR;
					SET @ProcedureLocation = 'Signature';
				
				 If @ErrorStatus = 0
					BEGIN	
						INSERT INTO Signature.signatures(PersonID, SignatureID, ModifiedDate, ModifiedBy)
							Values (@PersonID, @TempSignatureID,SYSDATETIME(),@ModifiedBy)
							
							SET @TempSignaturesID = @@IDENTITY;
							SET @ErrorStatus =@@ERROR; 
							SET @ProcedureLocation ='Signatures';
					END		
				IF @ErrorStatus =0
					BEGIN	
						SET @ProcedureLocation='';
						SET @success =1;
						COMMIT TRANSACTION;
					END
				ELSE
					BEGIN
						SELECT @ProcedureLocation = 'Insert failed at:' +@ProcedureLocation;
						RAISERROR( @ProcedureLocation,16,1);
					END 
		END
	END TRY
	

		BEGIN CATCH
		--Add in some granularity by returning an error id that indicates whether the failure was in Signature or Signatures.
			  ROLLBACK TRANSACTION;
			  --We are ignoring @@Error because it returns 50000 whenever a string is passed to RAISERROR
				--We only care if the error was not raised by SSE
				IF @@ERROR <> 50000
					BEGIN
						SELECT @ErrorStatus = @ErrorStatus + CONVERT(nVarchar(50), @@Error);
					END
			  SELECT @ProcedureLocation = @ProcedureLocation + '4001 ' +@ErrorStatus;
			  SET @Success =0;
			  RAISERROR(@ProcedureLocation, 16, 1);
			 
		END CATCH;

		
	













GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Collection of XML schemas for the AdditionalContactInfo column in the Person.Contact table.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'XML SCHEMA COLLECTION',@level1name=N'AdditionalContactInfoSchemaCollection'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Contains objects related to names and addresses of customers, vendors, and employees' , @level0type=N'SCHEMA',@level0name=N'Person'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Yearly Certification and Signature' , @level0type=N'SCHEMA',@level0name=N'Foodshelf', @level1type=N'TABLE',@level1name=N'FoodShelfCertification'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Makes each row unique for those who utilize the service more than once' , @level0type=N'SCHEMA',@level0name=N'Foodshelf', @level1type=N'TABLE',@level1name=N'FoodTypeGiven', @level2type=N'CONSTRAINT',@level2name=N'UK_FoodTypeGivenRecord'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is the electronic signature capture table.' , @level0type=N'SCHEMA',@level0name=N'Foodshelf', @level1type=N'TABLE',@level1name=N'Signature'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ID being used instead of the actual code because it may be possible to avoid duplicate addresses in the future' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'Address', @level2type=N'COLUMN',@level2name=N'AddressTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The clientPersonID is the PersonID of the client. All in the household are stored here in the PersonID column, except for the client. This ties household members to the client' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'FamilyRelationships', @level2type=N'COLUMN',@level2name=N'ClientPersonID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Lookup Table for Family Relationships. Data source is client' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'FamilyRelationships'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is called IncomeSourceRowID because we already have IncomeID from the LUIncomeType, avoid confusion!' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'Income', @level2type=N'COLUMN',@level2name=N'IncomeSourceRowID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The Person can have multiple income sources, but we only want to record each source once, thus uniqueness' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'Income', @level2type=N'CONSTRAINT',@level2name=N'UK_IncomeSource'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This table lists all languages spoken by employee or volunteer' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LanguagesSpoken'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key for AddressType records.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUAddressType', @level2type=N'COLUMN',@level2name=N'AddressTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Address type description. For example, Billing, Home, etc.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUAddressType', @level2type=N'COLUMN',@level2name=N'AddressType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date and time the record was last updated.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUAddressType', @level2type=N'COLUMN',@level2name=N'ModifiedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key (clustered) constraint' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUAddressType', @level2type=N'CONSTRAINT',@level2name=N'PK_AddressType_AddressTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Types of addresses stored in the Address table. ' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUAddressType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'City for the hierarchy State, County City, PostalCode' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUCity'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key for ContactType records.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUContactType', @level2type=N'COLUMN',@level2name=N'ContactTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Contact type description.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUContactType', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date and time the record was last updated.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUContactType', @level2type=N'COLUMN',@level2name=N'ModifiedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key (clustered) constraint' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUContactType', @level2type=N'CONSTRAINT',@level2name=N'PK_ContactType_ContactTypeID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Lookup table containing the types of contacts stored in Contact.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUContactType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is the lookup table for Country of Origin for clients. The list is based on the CIA World Facts Book' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUCountryOfOrigin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'List of counties' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUCounty'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Lookup Table for levels of education. Source is Client''s categories' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUEducationCategory'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is the ethnicity lookup table based on US Census Categories' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUEthnicity'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Where the client gets income. Source is organization''s categories' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUIncomeSource'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is the lookup table for race. It is based on US Census Categories' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LURace'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key for State records.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUState', @level2type=N'COLUMN',@level2name=N'StateID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ISO standard state code.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUState', @level2type=N'COLUMN',@level2name=N'StateCode'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'State.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUState', @level2type=N'COLUMN',@level2name=N'Name'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Date and time the record was last updated.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUState', @level2type=N'COLUMN',@level2name=N'ModifiedDate'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key (clustered) constraint' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUState', @level2type=N'CONSTRAINT',@level2name=N'PK_State_StateID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'State lookup table.' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'LUState'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Join table to allow multiple addresses per person' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'PersonAddresses'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This table associates a person with a particluar program (division) within the organization' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'Programs', @level2type=N'COLUMN',@level2name=N'ModifiedBy'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This table associates a person with one or more services within a program' , @level0type=N'SCHEMA',@level0name=N'Person', @level1type=N'TABLE',@level1name=N'ProgramServicesUsed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is the electronic signature capture table. It lives in its own schema and may be encrypted for security reasons' , @level0type=N'SCHEMA',@level0name=N'Signature', @level1type=N'TABLE',@level1name=N'Signature'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Only one SSN per person!' , @level0type=N'SCHEMA',@level0name=N'SSN', @level1type=N'TABLE',@level1name=N'SSN', @level2type=N'CONSTRAINT',@level2name=N'UK_SSN'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The types of jobs that the volunteer can do' , @level0type=N'SCHEMA',@level0name=N'Volunteer', @level1type=N'TABLE',@level1name=N'VolunteerJobs'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "FoodshelfRules (Foodshelf)"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 230
               Right = 504
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 4350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'vGetFoodshelfRules'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'vGetFoodshelfRules'
GO
USE [master]
GO
ALTER DATABASE [ChamplainCharityLLC] SET  READ_WRITE 
GO
