I'm encountering the same issue as in GO statements blowing up sql execution in .NET and tried implementing solution offered by Matt Johnson and am asking for assistance in getting it to work. I've been working with C# for a couple months so I'm still very green.
How is this called? I tried
var cmd = SplitSqlStatements(cmd);
but get an error:
'Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string'
Don't fully understand Regex.Split but my GO string is "\r\nGO\r\n" so would I change that split from
@"^\s*GO\s* ($ | \-\- .*$)"
to@"^\r\nGO\r\n$ | \-\- .*$)"
? I have no idea what| \-\- .*$
does.- My strings concatenate with + but I see @" at the beginning. Does this mean I need to get rid of the + concatenate?
- My strings have + '\n' + where I was trying to insert a newline, can these be replaced with System.Environment.Newline or should they be removed entirely?
Code:
private static IEnumerable<string> SplitSqlStatements(string sqlScript)
{
// Split by "GO" statements
var statements = Regex.Split(
sqlScript,
@"^\s*GO\s* ($ | \-\- .*$)",
RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
// Remove empties, trim, and return
return statements
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim(' ', '\r', '\n'));
}
Examples of my strings:
string sqlHeader = " Use " + "R04_FDW " + "\r\nGO\r\n" + "SET ANSI_NULLS ON" + "\r\nGO\r\n" + "SET QUOTED_IDENTIFIER ON" + "\r\nGO\r\n" + "SET ANSI_PADDING ON" + "\r\nGO\r\n";
string sqlName = "CREATE TABLE " + dwSchema + "." + dwTN + " (" + '\n';
string sqlNonCluster = "CREATE UNIQUE NONCLUSTERED INDEX [ak_" + dwTN + "__Sta3n_PrimaryKeys]" + " ON [" + dwSchema + "].[" + dwTN + "]" + '\n' + "(" + '\n';
SqlCommand cmd = new SqlCommand(sqlHeader + sqlName + sqlColumns + sqlFoot + sqlCluster + sqlNonCluster, vx130);