I am trying to build a view that will display data from an existing MSSQL 2000 table with look-ups to display IDs instead of the name values in the table. If the name value doesn't exist, I want it to add it into the reference/look-up table. Take the following look-up table of group ID's and Names:CREATE TABLE #groups ( id int IDENTITY, [name] varchar(10) )INSERT INTO #groups ([name]) VALUES ('Sales')INSERT INTO #groups ([name]) VALUES ('Support')
Here is the report that is imported daily:CREATE TABLE #report ( id int IDENTITY, [name] varchar(10), [group] varchar(10), [location] varchar(10) )INSERT INTO #report ([name],[group],[location]) VALUES ('Jason','Sales','New York')INSERT INTO #report ([name],[group],[location]) VALUES ('Steve','Sales','Paris')INSERT INTO #report ([name],[group],[location]) VALUES ('Richard','Support','New York')
I want the view to return:id | Name | Group | Location1 | Jason | 1 | New York2 | Steve | 1 | Paris3 | Richard | 2 | New York
And then if the report is updated the next day and a new marketing group is created:INSERT INTO #report ([name],[group],[location]) VALUES ('Tim','Marketing','Paris')
I want it to add "Marketing" to the groups table when the view is called:id | Name | Group | Location1 | Jason | 1 | New York2 | Steve | 1 | Paris3 | Richard | 2 | New York4 | Tim | 3 | Paris
I need to be able to create a look-up for Location as well (and the actual database has 9 columns that need to be looked up.)I tried to create a function called getGroup that would return the ID number for the group after checking if it exists, but the following code doesn't work. From what I understand you can't call INSERT or call stored procedures from within a function. Is there an easy way to accomplish this? CREATE FUNCTION getGroup (@value varchar(10)) RETURNS int AS BEGIN IF NOT EXISTS (SELECT * FROM #groups WHERE name LIKE @value) INSERT INTO #groups([name]) VALUES (@value) @id = SELECT * FROM #groups WHERE name LIKE @value) RETURN @id ENDCREATE VIEW showreport AS SELECT id, name, getGroup(group) As group, location FROM #report