.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

using sp_executesql with different parameters

Posted By:      Posted Date: October 15, 2010    Points: 0   Category :Sql Server

I've recently learned that it's much better to use sp_executesql with parameters instead of Execute for dynamic queries. The problem I am facing is that I have different parameters that are passed into my WHERE clause depending on the filters user selected on the website. Below is the example of my query. In this query there are 2 parameters: Category and Price. Sometime Price should be used in the WHERE and sometimes it shouldn't. But how can I define one SP to handle different scenarious?

Thank you in advance.


DECLARE @Category nvarchar(40)
DECLARE @Price int
set @Category=130
set @Price=125

SET @SQLString = 'SELECT distinct TOP 5 Products_Brand As Brand, Count(DISTINCT Products_pID) As CNT '
SET @SQLString = @SQLString  +
   'FROM _dta_mv_0_9987  WITH (NOEXPAND) ' +
   'LEFT OUTER JOIN Address ON ProductsLocation_aID = Address.aID ' +
   'WHERE ((ProductsLocation_aID = -1) OR (Address.City LIKE 'gft' AND Address.State LIKE 'tx'  )) ' +
   'and products_subcategory = @ParamCategory ' +
   'and productslocation_price>@ParamPrice' +
   ' GROUP BY Prod

View Complete Post

More Related Resource Links

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

How to Encrypt Query String Parameters in ASP.NET

Encrypt Query String Parameters in ASP.NET.u can send secure data one page another page u can also use query string to encrypt

view state vs request parameters


If  the view state is the data entered into the form fields then they are supposed to be available in the request parameters or request body. Then why would we need view state for?


FormView -- Parameters and asp:Table


I've already solved this problem to my satisfaction, I just want to know WHY it works this way.

I have a FormView control bound to an ObjectDataSource.  Let's say our data source is a hypothetical table with three columns:  id, name, age.  Why is it that when I use the <asp:Table> element inside of the FormView, the parameter values are not set, but when I use the standard <table> tag, it works fine?

This seems like a .NET problem to me.  I expect the <asp:Table> element to work in the same way as <table> because they are, for all intents and purposes, the same thing.  Am I missing something?

linqdatasource parameters question



I'm currently getting to know the linqdatasource control. What would happen if several WHERE parameters are added to the linqdatasource control declaritively in the aspx page but no WHERE clause is defined? 

1. is there any issue with setting up multiple WHERE parameters in the aspx markup for linqdatasource but then deciding which ones actually get used at runtime by setting the actual WHERE clause at run time? Would the unused parameters simply be ignored and cause no issues?

2. when you need to modify WHERE clause or WHERE parameters at runtime do you need to do so in an event handler? such as linqdatasource.selecting?
I see from the above link it is possible, but is that the standard way to handle controlling filtering in code behind for linqdatasource?

2b. if you use an event such as linqdatasource.selecting to add where parameters and/or modify the where clause in code will that also break the builtin sorting and paging support of the linqdatasource with a gridview? 

Optional named parameters work pretty well

Rob has found a use for dynamic: http://blog.wekeroad.com/2010/08/06/flexible-parameters-with-csharp Yay! Let's celebrate! Well, I was a little puzzled because I don't think it quite adds up in the specific example he chose (although please see no aggressiveness here: Rob's a friend; peace!). The idea is to have the same flexibility that a dynamic language can offer in terms of evolution of an API. Here's his original Ruby example: def my_method(args)   thing_one = args["thing1"]   thing_two = args["thing2"] end my_method :thing1 => "value", :thing2 = Time.now The idea, which is quite common in dynamic languages, is that instead of passing a list of predetermined parameters in a specific order, you...(read more)

SqlDataSource and Parameters query


Hi everyone,

I'm on the edge wondering is it possible ? I have got 2 questions. Please help me out.

1. I have a GridView on my page and it uses sqldatasource with parameterized query. What I want to do is, on page load (where nothing has been selected so no parameter supplied), I want it to query everything (something like SELECT * FROM [this_table]) but since my SelectCommand is something like

SELECT * FROM [this_table] WHERE [this_column] = @someParameters AND [that_column] = @someParameters.

Can I play around with default value to achieve something like that but how ? Now, when the page loads, it doesn't show anything (No Gridview).

2. On my page, I made something like (username, gender, address, and more) and one single search button. That means, no single control enable auto postback. What I am trying to accomplish is building dynamic query

(if username specifed -> SELECT * FROM [this_table] WHERE [username] LIKE @username).

If both username and gender are specified (SELECT * FROM [this_table] WHERE [username] LIKE @username AND [gender] = @gender) and you know the rest. How can I do this using GridView and SqlDataSource ? To my knowledge, I can only specify one SELECT statement in a sqldatasource.  I am stucked and desparately looking for help. Thanks all.

WCF DataService - Global Parameters


Greetings.  I am searching for a way to provide a couple "global" parameters to my WCF DataService.

What I would like to be able to do is set a couple properties on the server which will be held onto by the server for future queries by the client. 

For example, it would be great when I create my client if in the constructor I can just say: 

MyDataService service = new MyDataService("http://somurl/myservice.svc?param1=value1¶m2=value2


 I can then use param1 and param2 when a client calls my service and use QueryInterceptors to provide filters to the queries.  I want to avoid having to write custom WebGet methods.

If there is a way to accomplish this; great!

If there is a way to accomplish this with just 1 call; even better!

Passing Parameters through sub reports



I am trying to use a parameter field where there is a subreport in my main report but i keep getting the error "subreport cannot be shown" when running the report. Any ideas please.

p.s - I have just set the parameters the same in the subreport as the main report.



Passing report parameters by report viewer


I have 4 parameters in which 3 are passed in report and 1 is passed through report viewer. I have made a parameter in SSRS called CandidateId to which I want to pass the value. The code for report viewer is:

 intReportID = Convert.ToInt32(Request.QueryString["ReportID"
 CandId = Convert.ToString(Session["CandidateId"
lblReportName.Text = dtReport.Rows[0]["ReportName"
SSRSReportViewer.ShowCredentialPrompts =false

 SSRSReportViewer.ServerReport.ReportServerCredentials = new
SSRSReportViewer.ProcessingMode = Microsoft.Reporting.WebForms.


 SSRSReportViewer.ServerReport.ReportServerUrl = new

SSRSReportViewer.ServerReport.ReportPath = dtReport.Rows[0]


 Microsoft.Reporting.WebForms.ReportParameter[] theparams = new

theparams[0] = new
, CandId);
theparams[0].Visible = false

How to pass parameters to MDX through URL?


I have an SSRS report. I created it using BIDS and it uses a Sql Server Analysis Service data source.  The data source query is an MDX query with one parameter: @region, a default value has been set for this parameter.  The value which @region takes looks like [USA].[Northeast].[New Hampshire].[Coos County].

The MDX query goes like this:

Select ....


WHERE StrToMember(@region)

This report runs properly inside BIDS or through web browser after deployment.  In my report manager at http://localhost/Reports, I am able to view this report by selecting the value for the @region parameter from a dropdownlist, which contains such values as

Coos County
Cheshire County
Sullivan County
Strafford County
... ...

I know that we can pass query parameters to SSRS through the URL. I have successfully done so with relational database which uses regular SQL. But, I have not succeeded in passing this @region parameter of my MDX query through the URL.

I tried the following:


It didn'

Rowlimit and PageFirstRow properties of listview as parameters to Listview Webpart


Hi ,

 I need to set the  Rowlimit  and PageFirstRow properties  of  listview  as  parameters to Listview Webpart

 And these parameters  will be passed from the custom provider webpart


name of the list will be provided in custom webpart's toolpane.

and i need to save this as list content type of list defs


Please provide me the guidance on this.



Problem with Finder method with parameters



Could someone explain me how to provide some value to the parameters in a finder method. For exemple I know that the BDC list WP use this method. Is there a way to provide some value for those parameter at runtime? I really don't understand (even after some deep search on the web) where are the values for the parameters from and how we can connect to them. Even with C# code I can't find any information on how it work.

I don't want to define my parameters as filter in the ADF because then I will have this filter section in my BDC list WP (or is there a way to get rid of that?). Actually one of the parameter should be automatically calculated from a value in a SP list, the other parameter should be provided by my own filter web part.

Thank you for your help.

Need to pass parameters from URL to fields in Custom List


I have a complex customized list and I need to pass parameters of two fields so that when the 'Questionnaire' is completed and subsequentially opened after initial submission, it will retrieve the Number and GUID automatically in respective fields. I send an email out with a link to the 'Form' that carries the parameters. I am trying to use the following javaScript but am unsure as to where to place this on the SharePoint page for it to work.



<script type="text/javascript">

function loadFormVars()
getQuerystring('CustodianGUID', 'ctl00_m_g_d08916d8_7224_4665_be72_2de381f45985_ff46_1'); ///replace
customerGUID and form field name
'ctl00_m_g_d08916d8_7224_4665_be72_2de381f45985_FormField11_ctl00_ctl00_TextField'); ///replace customerGUID
and form field name

alert("it works");

function getQuerystring(key, field)
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
document.getElementById(field).value = qs[1];


How to send parameters to the AJAX callback function


I need to send som parameters to the callback function of my AJAX call, how can i do that:



function DoSomething(id, textbox1)
  AjaxHandler.FindSomethingInDB(id, Callback);

function Callback(result, eventArgs)
  // Here i need to know the value of textbox1 from the function "DoSomething"


Preview Crystal Report from ASP.net without passing parameters


Hi Everyone,

Sorry couldn't think of any better Subject..

I am developing a User Reports Module using C#.Net using Visual Studio 2005. Basic purpose of this module is to allow user to be able to run their own Crystal Reports. i.e. if Users have their own Crystal Reports specific to their needs then we allow them to save them and view them from our user reports module.

So when user saves any report we save it on server and save the Physical path of that report in database. Now when user tries to view the report I get the location from database and load it. Which works ok. The issue now is those reports which have got parameters. 

I am not saving any information about parameters in their reports. So I do not have any information about Report Parameters.

This same application exists in VB6. What that VB application does is opens the Crystal Report and then Crystal report asks for needed parameters exactly as it will do if we try to open a crystal report using crystal report and preview it from there it asks for parameter values. 

How can I do that in C#.Net.

VB has got code like this

Global Appl As New CRAXDRT.Application
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend