sql server - Searching on a table whose name is defined in a variable -
Text after "
Simple problem, but maybe a simple solution, at least I have one on top of my head, but can not think again I am not the best to find the best solution.
I have a stored procedure, it selects the stored procedure on one base (in a basic form), it implies:
Select to mytable < / Code> OK, quite simple, except for the table name, there is no need to search on it, so we ended up with something very similar to this:
- Just variable INT set @metaInfoID = 1 declared @metaInfoTable will be used as the @metaInfoID declaration as VARCHAR Area to choose to give some reference (200) @metaInfoTable = MetaInfoTableName MetaInfos where MetaInfoID = @MetaInfoID VARCHAR (200) set select @sql announced = 'as @sql * the' + @metaInfoTable EXEC @ Sql So, I know it's finally bad, and can immediately see how I can do SQL injection attacks. So, the question is whether there is any way to achieve the same results without the creation of dynamic SQL? Or am I super, am going to be super careful in my client code?
To use
You have dynamic SQL if you do not know the table name. But yes, the value should be valid before you try to use it in a SQL statement.
Example
if exists (select * INFORMATION_SCHEMAkTABLES where TABLE_NAME = @ metaInfoTable) BEGIN - SELECT * FROM @metaInfoTable dynamic SQL END This will ensure that there is a table with that name. This is clearly an overhead because you are inquiring about INFORMATION_SCHEMA. Instead, you can include only some valid characters valid in @metaInfoTable:
- Running dynamic SQL only if the table name's value is 0-9, az, AZ, underscore or spaces ( Bracket in the square, if it contains empty space) IF NOT @metaInfoTable '% ^ [0-9a-zA-Z _]%' BEGIN - Select SELECT * FROM @metaInfoTable Dynamic SQL END < / Pre>
Comments
Post a Comment