views:

161

answers:

4

What I am trying to do is create some arbitrary sql command with parameters, set the values and types of the parameters, and then return the parsed sql command - with parameters included. I will not be directly running this command against a sql database, so no connection should be necessary. So if I ran the example program below, I would hope to see the following text (or something similar):

WITH SomeTable (SomeColumn)
AS
(
    SELECT N':)'
    UNION ALL
    SELECT N'>:o'
    UNION ALL
    SELECT N'^_^'
)
SELECT SomeColumn FROM SomeTable

And the sample program is:

using System;
using System.Data;
using System.Data.SqlClient;

namespace DryEraseConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            const string COMMAND_TEXT = @"
WITH SomeTable (SomeColumn)
AS
(
    SELECT N':)'
    UNION ALL
    SELECT N'>:o'
    UNION ALL
    SELECT @Value
)
SELECT SomeColumn FROM SomeTable
";
            SqlCommand cmd = new SqlCommand(COMMAND_TEXT);
            cmd.CommandText = COMMAND_TEXT;
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "@Value",
                Size = 128,
                SqlDbType = SqlDbType.NVarChar,
                Value = "^_^"
            });
            Console.WriteLine(cmd.CommandText);
            Console.ReadKey();
        }
    }
}

Is this something that is achievable using the .net standard libraries? Initial searching says no, but I hope I'm wrong.

+4  A: 
Joel Coehoorn
Thanks, this is exactly what I needed to hear. Knowing that sp_executesql is what is called behind the scenes explains everything.
Burg
+1  A: 

I would be tempted to look into using LINQ as it will give you the control you want in your C# code.

kevchadders
Unfortunately, Linq-To-Sql is an ORM for the most part, and that is not what I am doing. What I need to do is some advanced T-SQL generation (bulk inserts, for example).
Burg
+1  A: 

Joel Coehoorn is right, it's not just a simple string substitution or escape character adding, etc.

You can, however, view your parameters to see if your values are as you want them:

foreach (IDataParameter i in cmd.Parameters)
{
    Console.WriteLine(i.Value.ToString());
}
JYelton
+1  A: 

THe SQLCommand object does not swap out the params for the value in the command text and run that. It calls the sp_execute sql with the exact text you supply and then supplies the list of paramaters. Use SQL profiler against a database and you will see what i mean.

What is it you are actually trying to acheive here?

Ben Robinson
I was trying to find an easy way to generate some sql command text (these commands would be executed upstream, not on the spot). The functionality of the queries would be far too complex for Linq-To-Sql to handle (don't think LINQ does bulk inserts, T-SQL, and the like). I was also hoping I could avoid doing the StringBuilder approach as well.
Burg