C # multi-line strings allowing variable invocation

I have googled, but I can not find the answer to this question:

I know about multiline strings in C #. But how can I create a line like:

string temp = @"DECLARE @rolename varchar(max) SET @rolename ='***' EXEC sp_addrolemember N'db_execute',@rolename" 

* means that I need to process a variable that has some value (object.variable).

Is it possible?

+4
source share
4 answers

You can use string.Format :

 string temp = @"DECLARE @rolename varchar(max) SET @rolename ='{0}' EXEC sp_addrolemember N'db_execute',@rolename"; string result = string.Format(temp, object.variable); 

Note that you are open to sql-injection attacks if object.variable is (or may be in the future) a user-defined variable.

+5
source

.NET supports multi-line strings, of course. The syntax @"..." is just a shortcut to make it easier to use the language. However, in your specific example, you should not try to combine the value in: this whole example should be executed through parameters:

 cmd.CommandText = "EXEC sp_addrolemember N'db_execute',@rolename"; cmd.Parameters.AddWithValue("rolename", yourRoleName); 

Update: msdn check, the second parameter is the member name, but you can also use:

 cmd.CommandText = "sp_addrolemember"; cmd.CommantType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("rolename", "db_execute"); cmd.Parameters.AddWithValue("membername", yourMemberName); 
+10
source

Use the string.Format method:

 string temp = string.Format(@"DECLARE @rolename varchar(max) SET @rolename ='{0}' EXEC sp_addrolemember N'db_execute',@rolename", variable); 
+3
source

Yes, it is possible:

 string temp = string.Format(@"DECLARE @rolename varchar(max) SET @rolename ='{0}' EXEC sp_addrolemember N'db_execute',@rolename", variable); 
+1
source

Source: https://habr.com/ru/post/1498178/


All Articles