Monday, February 20, 2012

Need help writing a custom View in Sql Server

Does anyone knowif the following sql view is possible to write and execute as a view script?

**********find employee matching the given UserID*************
SELECT * FROM Employees WHERE EmployeeID=@.UserID

***********find client matching the given ClientID**********
SELECT *FROM Clients WHERE ClientID=@.ClientID

**********findall contacts and events associated with ClientID*********
SELECT *FROM Contacts WHERE Contact.ClientID=@.ClientID
SELECT *FROM Events WHERE Event.ClientID=@.ClientID

*********selectall audits with Key values matching the primary keys of each client, contact orevent*********
SELECT *FROM Audit Where Key In (Client.ClientID, Contact.ContactID, Event.EventID)

I basicallyneed to find a employee based on its ID. Then I need to find any records from the table Auditwith Key values matching the given fields in the results of any clients, contacts events that were returned from the previous select statements. Is this possible?

You need list all your table's schema. If they are related, you can write a query with JOINs and put into a view.|||Well I don't want to JOIN them. I just want to select certain items out of the Audit table based on the key values taken from records retrieved from Clients, Contacts and Events. I just need to return records matching the schema in Audit, nothing else.|||

You could do something like this: If this is not what you are looking for you need to detail the structure of each of the tables and the columns that would be used in the [Key] column in the Audit table.

Declare @.table table (KeyIdint)INSERT INTO @.table SELECT <column>FROM EmployeesWHERE EmployeeId = @.UserIdINSERT INTO @.table SELECT <column>FROM ClientsWHERE ClientID=@.ClientIDINSERT INTO @.table SELECT <column>FROM ContactsWHERE Contact.ClientID=@.ClientIDINSERT INTO @.table SELECT <column>FROM EventsWHERE ClientID=@.ClientIDSELECT *FROM AuditWHERE [Key]In (SELECT KeyIdFROM @.table)

|||

You can format and execute a string similar to:

CREATE VIEW MyView as Select * from MyTable where ID = 55


But the view will be hardcoded to the ID of 55...probably not very useful.

A view itself cannot take parameters but I read that you can do it with user-defined functions.

|||

If you need to pass a parameter to it you need to use a stored procedure, not a view.

No comments:

Post a Comment