In my programming task I’ve gone down a dark alley and wished I hadn’t, but there is no turning back now.
I’m building up a SQL statement where the table name, column name and id value are retrieved from query string parameters i.e. ("SELECT [{0}] FROM [{1}] WHERE [Id] = {2};", c, t, id)
But it isn’t as bad as it looks, I’m protected:
- Only authenticated users (i.e. signed in users) can execute the
Page_Load - I’m checking that both the table and the column exists beforehand
(usingGetSchemaetc.) - I’m checking that the Id is an integer beforehand
- All my tables have Id columns
- The database connection is reasonably secure
The field value is expected to be of type NVARCHAR(4000) or NVARCHAR(MAX) so I’m avoiding ExecuteScalar and I’m trying out LINQ ExecuteQuery because I like LINQ. But I’m a bit out of my depth again.
I’ve got this far:
Dim db As New MyDataContext
Dim result = db.ExecuteQuery(Of ITable)("SELECT [{0}] FROM [{1}] WHERE [Id] = {2};", c, t, id)
- Is this the right way to go?
- How do I get first row and first column value?
- Is there a better alternative?
P.S. It’s a SQL Server 2005 database
Any help appreciated.
Thanks.
SQL Server requires the tables ans columns to be statically known. You can’t provide them using command parameters. You can’t say
because the table name can’t be a variable.
You need to build the SQL string with C# ensuring proper escaping of identifiers. Escaping works like this:
This is safe.