Combine View and Select into one INSERT statement

Posted on 2016-10-12
Last Modified: 2016-10-12
Hi all.

I have the following INSERT statement that uses a VIEW (named ActiveAGs), if any record in the AGmembership table is not present in the ActiveAGs VIEW then insert into the AG table. So, the records might not be in the AG table at all OR they might be in the AG table but with a status of INACTIVE which means they have to be entered into the AG table (the default value when inserting a record is ACTIVE).

Any idea how I can do this without having to create a view and then use that view in the INSERT statement, is there a way to do it in just one statement?

Thank you in advance.

SELECT DISTINCT AGmembership.[GName], AGmembership.AG
FROM         AGmembership LEFT OUTER JOIN
                      ActiveAGs ON AGmembership.[GName] = ActiveAGs.[GName] AND AGmembership.AG = ActiveAGs.AG
WHERE     (ActiveAGs.[GName] IS NULL) AND (ActiveAGs.AG IS NULL)

Open in new window

Here is the ActiveAGs View:
SELECT     [GName], AG, Status
FROM         dbo.AG
WHERE     (Status = 'Active')

Open in new window

Question by:printmedia
LVL 69

Accepted Solution

Scott Pletcher earned 500 total points
ID: 41840921
FROM         AGmembership AGm
        SELECT 1
        FROM ActiveAGs AAG
        WHERE AAG.GName = AGm.GName AND AAG.AG = AGm.AG AND AAG.Status = 'Active'

Author Closing Comment

ID: 41840933
Worked great. Thanks!

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question