roger's picture

SQL Server: INSERT WHERE NOT EXISTS

Because whenever I've been away from SQL Server for more than a couple of weeks, I forget.

/* Some tables. */
CREATE TABLE X (
	Name VARCHAR(20)
)
GO

CREATE TABLE Y (
	Name VARCHAR(20)
)
GO
/* Some sample data. */
INSERT INTO X(Name) VALUES('Alice')

INSERT INTO Y(Name) VALUES('Alice')
INSERT INTO Y(Name) VALUES('Bob')
INSERT INTO Y(Name) VALUES('Bob')
INSERT INTO Y(Name) VALUES('Charles')
/* The interesting bit. */
INSERT INTO X(Name)
	SELECT DISTINCT Name FROM Y
	WHERE NOT EXISTS ( SELECT * FROM X WHERE X.Name = Y.Name )

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <blockquote> <br> <code> <dd> <dl> <dt> <hr> <h1> <h2> <h3> <i> <img> <li> <ol> <p> <pre> <table> <td> <th> <tr> <tt> <u> <ul>
  • Images can be added to this post.

More information about formatting options