Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table name as query parameter #659

Closed
vadamlyuk opened this issue May 12, 2021 · 2 comments
Closed

Table name as query parameter #659

vadamlyuk opened this issue May 12, 2021 · 2 comments

Comments

@vadamlyuk
Copy link

vadamlyuk commented May 12, 2021

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
Copy link
Contributor

tc-hib commented May 12, 2021

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
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants