Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Script for inserting records

Author  Topic 

Hammerklavier
Starting Member

26 Posts

Posted - 2015-01-12 : 13:52:03
Hi,

I'm faced with the task of creating a script that will do a series of inserts. The insert statements will look the same except for one value, which will differ for each insert.

For simplicity's sake, here is a table with some inserts:


CREATE TABLE
#MyTable (
MyPk INT IDENTITY,
MyValue VARCHAR(24)
)

INSERT INTO #MyTable (MyValue) VALUES ('Whatever')
INSERT INTO #MyTable (MyValue) VALUES ('Something')
INSERT INTO #MyTable (MyValue) VALUES ('Filler')
INSERT INTO #MyTable (MyValue) VALUES ('Who Cares')

SELECT * FROM #MyTable

DROP TABLE
#MyTable


Rather than having to modify the string for each individual update statement, I'm hoping there is a simple way to create a variable (perhaps an array) which holds an indefinite number of values, then have a loop which automatically does an insert for each specified value in the array. Is something like this possible? Or is there a preferred industry standard for this sort of thing that I should use instead?

Thanks!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2015-01-12 : 14:04:56
Where are the values coming from? The application? You can just put it into a string with commas as the delimiter and then parse it on the T-SQL side with a function such as this one: http://www.nigelrivett.net/SQLTsql/ParseCSVString.html

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

Hammerklavier
Starting Member

26 Posts

Posted - 2015-01-12 : 15:56:45
Thanks for the suggestion, tkizer! I'll give that a try.

Go to Top of Page
   

- Advertisement -