- Community Pick
- Experts Exchange Approved
First of all, this is a work in progress. There's bound to be little bugs that I haven't worked out yet because I literally just wrote it 10 minutes ago when asked to do this. But as updates to this happen, I will post post new iterations of "SQL Insert Generator".
Secondly, this is for SQL 2005 and later only. Trying to do this working within the limitations of the varchar() and nvarchar() data types in SQL 2000 would have been too much of a pain in the butt. But if you are working with fairly narrow tables then it should work in SQL 2000. Just change the nvarchar(MAX) variables to nvarchar(4000).
The procedure works as follows. You pass in some simple parameters. The schema and table name are obvious. The @IDField parameter isn't quite so obvious so I'll explain. This is the field used to select which values you want to export. This is necessary, at least for me, because when I am generating these types of inserts I am doing so only for a range of data in a column. @IDMin and @IDMax are inclusive range limiters for the @IDField. @IncludeIdent says whether or not to include a field if it has an identity property on it. This script, intentionally, does not include the necessary SET IDENTITY_INSERT ON statement in order for the resulting SQL to run, that's something you will need to include with the output. Lastly @IncludeIfNot says whether or not to include an "IF NOT EXISTS" statement on the resultant insert statement. This is needed for making code that does not fail when run more than once or produce an undesirable result.
Now let's talk about an example. Let's say that you have a table called dbo.PurchasedGoods and you want to generate an insert statement for fields where the PurchasedGoods_Id value is from 1 to 100. The syntax of the command would be as follows:
Variations of the last two parameters can be used depending upon what data you want to be generated.
I hope this comes in handy for you as it already has for me. If you notice any problems, or something doesn't work with your data, please post a comment and I will address it or post a new revision. To keep up to date on changes to this script (http://bit.ly/SQLinsGen) as it evolves, and to find other useful scripts, stop by my site at http://www.sqlservernation
BrandonGalderisi
by: matthewspatrick on 2010-10-29 at 17:44:55ID: 20950
Thanks for sharing, this is brilliant! I wish I had had something like this available the few times I had had to script out the complete recreation of a table, including the values :)
Patrick