0

Sonar rule link: https://rules.sonarsource.com/csharp/RSPEC-3649

I have a sql string that takes DB name as parameter. It's like: UPDATE [@DBNAME].[dbo].[MyTable] SET [Column]='1'

Sonar doesn't accept this string but I can't give DB name as SqlCommand parameter.

Does anyone has an idea to fix this?

I am looking for a solution other than suppress or turning off Sonar Analysis.

ps: I use SqlServer 2012.

sosa
  • 63
  • 1
  • 8
  • Possible duplicate of [Turning Sonar off for certain code](https://stackoverflow.com/questions/10971968/turning-sonar-off-for-certain-code) – BWA Nov 20 '18 at 12:31
  • 3
    Either suppress the warning (this is a legitimate use case for string replacement) or change the approach to use `SqlConnection.ChangeDatabase` before issuing the `UPDATE` (or a new `SqlConnection` with a correct `Initial Data Source`). – Jeroen Mostert Nov 20 '18 at 12:32
  • @JeroenMostert in this case when you control string in 100% I think string replacement is ok. But generally you have right. – BWA Nov 20 '18 at 12:37
  • All such tools have a chance of flagging something as wrong where you know more about the situation. As long as you have made sure that the database name isn't something the user can type in directly and that is from a verified and secure source, then you should tell Sonar to ignore this particular statement. – Lasse V. Karlsen Nov 20 '18 at 12:39
  • @BWA Sonar doesn't accept string replacement. Also, suppress is my last option, I'm looking for a solution. – sosa Nov 20 '18 at 12:40
  • 2
    Suppressing *is* a solution. These tools are not all-knowing. From your question, I can't know if the string is indeed properly vetted by the application, and neither can Sonar, hence the warning. If you, the developer, know this string is fine, then you have to suppress, because the database name is *not* parameterizable in T-SQL. Removing it from the statement means rewriting code. – Jeroen Mostert Nov 20 '18 at 12:41
  • 1
    Well, thinking about it, I guess you *can* make the name parameterizable, but you have to give up the single statement and submit a batch: `DECLARE @sql NVARCHAR(MAX) = REPLACE('UPDATE @DBNAME.[dbo].[MyTable] SET [Column]=''1''', '@DBNAME', QUOTENAME(@dbname)); EXEC (@sql);`. This wouldn't be my first choice, especially not if you have lots of statements that do this -- `ChangeDatabase` would look a ton more attractive then. – Jeroen Mostert Nov 20 '18 at 12:44
  • Does Sonar accept `USE @db_name;` ? – serge Nov 20 '18 at 12:55
  • @serge SQL Server does not allow using `USE @db_name;`... – Zohar Peled Nov 20 '18 at 13:35
  • Thank you @JeroenMostert, SqlConnection.ChangeDatabase has worked. – sosa Nov 20 '18 at 13:36

0 Answers0