Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Insert statement using multiple values without repeating each line

$
0
0

I'm trying to create a Insert statement where it checks to see if a row exists and if not, then the row gets added in but I have one column that changes in each insert line.

So for example,

DECLARE LName char(12)

SET Lname='Smith'

If not exists (select * from myTable where Firstname = 'John' and Lastname = Lname)

Insert into myTable (Firstname, Lastname)

Values ('John', LName)

Now I want LName to hold the values 'Smith','Robertson','Snyder' and loop through this statement for as many values I have under LName (in this case 3). From my research, I found out that the only way you can have a variable holding multiple values is through a table. Problem though is that you can't use a column name in an insert statement.

The only way I can do this now is to copy and paste all the lines from SET to Values and reset the Lname each time which makes the query that much longer. Is there an easier way?


Viewing all articles
Browse latest Browse all 23857

Trending Articles