denisenkom / go-mssqldb

Microsoft SQL server driver written in go language
BSD 3-Clause "New" or "Revised" License
1.82k stars 495 forks source link

Table name as query parameter #659

Closed vadamlyuk closed 2 years ago

vadamlyuk commented 3 years ago

I understand that the following question is not related to go-mssqldb, but may be somebody knows...

Is it possible to use Named/Unnamed query parameter as a table name. I.e. is it possible to make query like this:

db.QueryContext(ctx, "select cont(*) as CNT from @TABLE_NAME", sql.Named("TABLE_NAME", "Test")) As result of such query I'm geting error: mssql: Must declare the table variable "@TABLE_NAME".

In case of: db.QueryContext(ctx, "select cont(*) as CNT from [@TABLE_NAME]", sql.Named("TABLE_NAME", "Test")) error is: mssql: Invalid object name '@TABLE_NAME'

The reason of that question is that I'd like to use query parameters to prevent sql injection problem, but I'd like to set table or column names in config file, so I have to think about sql injection problem...

tc-hib commented 3 years ago

You would need an indirection in the query itself. I don't think there's a simple way to do that. You can easily quote identifiers: enclose them between brackets and double the closing brackets they contain. You can use QUOTENAME in T-SQL for comparison. my table [1] should be quoted as [my table [1]]] You should have a look at this too: https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers?view=sql-server-ver15

kardianos commented 2 years ago

When you start doing that, you should just start constructing SQL in your application. If you must do it within T-SQL, you have to construct the full SQL then execute it with sp_exec.