Ok so I’m using C# to insert information into a table in a database server. It creates the SQL command based off of a bunch of if statements that add to it. I’m having an issue getting the statement to be created cleanly. I understand that to combine Insert statements in SQL Server we use:
INSERT INTO myTable
SELECT 'value1', 'value2'
UNION ALL
SELECT 'value3', 'value4'
UNION ALL
SELECT
etc
My issue is ordering them so that the statement will work regardless of which if statements it passes. For example,
function()
string sqltext = "INSERT INTO myTable"
if(cond1)
{ sqltext=sqltext + "SELECT 'v1', 'v2' UNION ALL" }
else if (cond2) {
sqltext = sqltext + "SELECT 'v3', 'v4' UNION ALL" }
In this case, if either condition returns by itself, the statement won’t work because the statement will end in UNION ALL. I hope this makes sense. Thoughts?
Make a list of selects
and
and finally