views:

421

answers:

1

I have an MS SQL function that is called with the following syntax:

SELECT Field1, COUNT(*) AS RecordCount
FROM GetDecileTable('WHERE ClientID = 7 AND LocationName = ''Default'' ', 10)

The first parameter passes a specific WHERE clause that is used by the function for one of the internal queries. When I call this function in the front-end C# page, I need to send parameter values for the individual fields inside of the WHERE clause (in this example, both the ClientID & LocationName fields)

The current C# code looks like this:

String SQLText = "SELECT Field1, COUNT(*) AS RecordCount FROM GetDecileTable('WHERE
                  ClientID = @ClientID AND LocationName = @LocationName ',10)";
SqlCommand Cmd = new SqlCommand(SQLText, SqlConnection);
Cmd.Parameters.Add("@ClientID", SqlDbType.Int).Value = 7; // Insert real ClientID
Cmd.Parameters.Add("@LocationName", SqlDbType.NVarChar(20)).Value = "Default";
               // Real code uses Location Name from user input
SqlDataReader reader = Cmd.ExecuteReader();

When I do this, I get the following code from SQL profiler:

exec sp_executesql N'SELECT Field1, COUNT(*) as RecordCount FROM GetDecileTable
(''WHERE ClientID = @ClientID AND LocationName = @LocationName '',10)',
N'@ClientID int,@LocationID nvarchar(20)',
@ClientID=7,@LocationName=N'Default'

When this executes, SQL throws an error that it cannot parse past the first mention of @ClientID stating that the Scalar Variable @ClientID must be defined. If I modify the code to declare the variables first (see below), then I receive an error at the second mention of @ClientID that the variable already exists.

exec sp_executesql N'DECLARE @ClientID int; DECLARE @LocationName nvarchar(20); 
SELECT Field1, COUNT(*) as RecordCount FROM GetDecileTable
(''WHERE ClientID = @ClientID AND LocationName = @LocationName '',10)',
N'@ClientID int,@LocationName nvarchar(20)',
@ClientID=7,@LocationName=N'Default'

I know that this method of adding parameters and calling SQL code from C# works well when I am selecting data from tables, but I am not sure how to embed parameters inside of the ' quote marks for the embedded WHERE clause being passed to the function.

Any ideas?

+1  A: 

was

SELECT Field1, COUNT(*) AS RecordCount FROM GetDecileTable('WHERE
ClientID = @ClientID AND LocationName = @LocationName ',10)

should

SELECT Field1, COUNT(*) AS RecordCount FROM GetDecileTable('WHERE
ClientID = ' + @ClientID + ' AND LocationName = ' + @LocationName,10)

your variables are used inside string where they are considered just as part of it.

Andrey
Thanks, but this doesn't fit the bill in this situation. The problem comes because of the embedded quotes in the sub-WHERE clause.
Marshall