I have many files for procedures, views, functions, etc.
I want to execute these files (creating components) in appropriate database on SQL Server 2005/2008.
Also the point is I want to execute them using C#.
Another point to mention, I want the application to be such that I can execute this files on a remote SQL Server too. Also client machine may not have osql,sqlcmd command tool.
Can someone please guide me on this.
This depends on what sort of files they are. If, for example, they only contain actual T-SQL commands (and aren’t batch files that you’d run in, say, SSMS, which would contain a batch separator like
GO), then you just need to create a connection, a command, then read the contents of the file and use that to populate theCommandTextproperty of the command.For example:
If it’s a batch file, you’ll need to split the file into individual batches and process those individually. The simplest method is just to use
string.Split, but bear in mind that it won’t respect SQL parsing rules when it splits (for example, ifGOappears within a SQL statement, it’s going to split the command up into two batches, which will obviously fail).More generally, you can see what you’d need to do here by modifying the code in this way:
The implementation of a function called
SplitBatchesis up to you.