vysakh
vysakh

Reputation: 266

c# multi line strings allowing variable calling

I have googled but cannot find an answer for this question:

I know about multi-line strings in c#. But how can I create a string like:

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

* represents there I have to delcare a variable having some value like (object.variable).

Is this possible??

Upvotes: 4

Views: 274

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460058

You could 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 for sql-injection attacks if object.variable is (or might be in future) a user defined variable.

Upvotes: 5

Irfan
Irfan

Reputation: 2771

Yes its possible:

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

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062550

.NET supports multi-line strings, sure. The @"..." syntax is just a shortcut to make it easier in the language. However, in your specific example you should not try to concatenate the value in: that entire example should be done via parameters:

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

Update: checking msdn, the second parameter is actually the member-name, but you might also be able to use:

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

Upvotes: 10

BartoszKP
BartoszKP

Reputation: 35891

Use string.Format method:

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

Upvotes: 3

Related Questions