Select Parameters With Gridview
I have a form that has 4 fields to fill in. I have a button that can add these fields to a sql database. I also want to put a button next to the "add" button so you can fill out the same fields and search for those values. Here's what i have so far. I want to select based on the fields, but i'm having trouble with the syntax of the parameters. I also want to add something, so if nothing is filled out in one of those boxes, it retuns back all records for the default value.
string strConnection = ConfigurationManager.ConnectionStrings["TimeAccountingConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnection);
String selectCmd = "SELECT * FROM users WHERE firstname = @firstame or lastname = @lastname or office = @office or team = @team";
SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@firstname", SqlDbType.VarChar, 50));
myCommand.SelectCommand.Parameters.Add("@firstname", txtFirstName.Text);
myCommand.Parameters.AddWithValue("@lastname", txtLastName.Text);
myCommand.Parameters.AddWithValue("@team", dwnTeam.Text);
myCommand.Parameters.AddWithValue("@office", dwnOffice.Text);
DataSet ds = new DataSet();
myCommand.Fill(ds, "users");
MyDataGrid.DataSource = ds.Tables["users"].DefaultView;
MyDataGrid.DataBind();
View Complete Forum Thread with Replies
Related Forum Messages:
SQL Wildcard - Parameters And Gridview
Hi There, I have created a gridview and a text box search field to list records from my database based on a search query. This works fine but what I would like to do is enable a wildcard search. So for example - if I enter fluff a record with the value flufflebot will still appear in my resultant gridview. My current SQL query looks like: SELECT dbo.myTable.*FROM dbo.myTableWhere Field1 = @Field1 Where @Field1 is a parameter returned from user input to enable wildcard: SELECT dbo.myTable.*FROM dbo.myTableWhere Field1 like @Field1 <- this is where i get stuck - I need to add % to the end of that to enable a wildcard search - but that breaks the parameter know this must be simple - appreciate any suggestions
View Replies !
Gridview Select
I am using a GridView which is select enabled. I have another sqldatasource control on my page which will run a SQL query but needs a parameter. This parameter is from a column (EmployeeID) of the selected row in the gridview. In the Sqldatasource control I have specified the parameter source as a control which is Gridview .But I dont know how to point to the EmployeeID column of the selected row.Please help.
View Replies !
Changing The SQLDatasource SELECT For A Gridview
I cant seen to change the Select command for a SQL Datasourcetry #1 SqlDataSourceProfilesThatMatch.SelectCommand = strSQLForSearch SqlDataSourceProfilesThatMatch.SelectParameters("ProfileID").DefaultValue = pProfileID SqlDataSourceProfilesThatMatch.SelectParameters("LoggedInUsersZipcode").DefaultValue = pUsersZipCode SqlDataSourceProfilesThatMatch.SelectParameters("ZipDistance").DefaultValue = pDistance NewProfilesThatMatchGridView.DataBind() try #2 SqlDataSourceProfilesToBeMatched.SelectParameters.Clear() SqlDataSourceProfilesThatMatch.SelectCommand = strSQLForSearch SqlDataSourceProfilesThatMatch.SelectParameters.Add("ProfileID", pProfileID) SqlDataSourceProfilesThatMatch.SelectParameters.Add("LoggedInUsersZipcode", pUsersZipCode) SqlDataSourceProfilesThatMatch.SelectParameters.Add("ZipDistance", pDistance) NewProfilesThatMatchGridView.DataBind() No errors but no rows show in the gridview. If I debug and get the value strSQLForSearch and paste it into a new SQL query window I get results. Any ideas???? Thanks
View Replies !
Select Just A Couple Of Rows Into Gridview
I am using a sqlDataSource to read my query and to put the rows into a gridview. Now I want to read just a couple of rows from my query based on a maximum number, also defined in the table. I have absolutely no idea how to do that..for example: I want to view only the 10 most recent subsciptions into my gridview. The subscriptions are stored into tabel Subscriptions which has values id, userid,date. Table Event has a parameter "maximum subscriptions" (which is 10 in my example) I hope it is clear enough?Thank you in advance!BlueiVeinz
View Replies !
Select Command Lost Thus Gridview Shows Nothing
Hi there,I am not sure how many of you have experienced this problem before but here is how to replicate it: Add a GridView, SqlDataSource and Button to a new projectSet the DataSourceID to the SqlDataSource objectSet AllowPaging to True on the GridViewWithin the Button1_Click sub, change the SqlDataSource.SelectCommand to a new Query e.g SELECT * FROM table WHERE ID > 1Run the project Click on another page, i.e. "3" on the GridView SqlDataSource.SelectCommand is now blank(!), thus Gridview displays nothing. Has anyone else found a solution to this annoying issue? Any help is appreciated.Regards
View Replies !
Need Gridview To Display Different Columns Based On New SELECT Statement
I have built an Advanced Search page which allows users to select which columns to return (via checkbox) and to enter search criteria for any of the selected columns (into textboxes). I build the SQL statement from the properties of the controls. Works great. My problem is getting my gridview control to play nicely. At first I used a SqlDataReader and bound the gridview to it, thus giving me the ability to run new SQL statements through it (with different columns each time). Worked nicely. But, per Microsoft, sorting can only be done if the gridview is bound to a datasource control like the SqlDataSource. So I wrote the code to handle sorting. No big deal; worked nicely. But I could not adjust the column widths programmatically unless bound to a datasource control like the SqlDataSource. And could not figure out a work around. So, I decided to use the SqlDataSource. Works great. Except, I cannot figure out how to run a new SELECT statement through the SQLDataSource and have the gridview respond accordingly. If I try to return anything other than the exact same columns defined declaratively in the html, it pukes. But I need to be able to return a new selection of columns each time. For example, first time through the user selects columns 1,2,3,4 – the gridview should show those 4 columns. The second time the user selects columns 2,5,7 – the gridview should those 3 columns (and ONLY those 3 columns). Plus support selection and sorting. I am desperate on this. I've burned 2.5 days researching and testing. Does anyone have any suggestions? Thanks, Brad
View Replies !
Sqldatasource, Does It Select If Not Bound To A Gridview, Formview On The Page?
Using 3.5 If I have a sqldatasource on the page, is it run if it is not bound to a data object like a gridview? Seems like if i want to access the data (like set a label text) from the sqldatasource I have to use code to first create a dataview then pick throught it. This seems like I'm running it twice. I'm new at .net so I dont know how to tell. I don't want to write data select code programatically when I can just through an SDS on the page, but wondered it it ran just because it's on the page.
View Replies !
Want Error Message To Appear When No Database Results Were Returned In GridView, Also Other GridView Issues.
Hi, I am seeking a hopefully easy solution to spit back an error message when a user receives no results from a SQL server db with no results. My code looks like this What is in bold is the relevant subroutine for this problem I'm having. Partial Class collegedb_Default Inherits System.Web.UI.Page Protected Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] WHERE [name] like '%" & textbox1.Text & "%'" SqlDataSource1.DataBind() If (SqlDataSource1 = System.DBNull) Then no_match.Text = "Your search returned no results, try looking manually." End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] ORDER BY [name]" SqlDataSource1.DataBind() End Sub Protected Sub reset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles reset.Click SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] ORDER BY [name]" SqlDataSource1.DataBind() End SubEnd Class I'm probably doing this completely wrong, I'm a .net newb. Any help would be appreciated. Basically I have GridView spitting out info from a db upon Page Load, but i also have a search bar above that. The search function works, but when it returns nothing, I want an error message to be displayed. I have a label setup called "no_match" but I'm getting compiler errors. Also, next to the submit button, I also have another button (Protected sub reset) that I was hoping to be able to return all results back on the page, similar to if a user is just loading the page fresh. I'd think that my logic would be OK, by just repeating the source code from page_load, but that doens't work.The button just does nothing. One final question, unrelated. After I set this default.aspx page up, sorting by number on the bottom of gridview, ie. 1,2,3,4, etc, worked fine. But now that paging feature, as long with the sorting headers, don't work! I do notice on the status bar in the browser, that I receive an error that says, "error on page...and it referers to javascript:_doPostBack('GridView1, etc etc)...I have no clue why this happened. Any help would be appreciated, thanks!
View Replies !
GridView Based On SQLServerDataSource Using A Select Union Statement, Impacts On Update And Insert?
I have a GridView dispalying from a SQLServerDataSource that is using a SQL Select Union statement (like the following): SELECT FirstName, LastNameFROM MasterUNION ALLSELECT FirstName, LastNameFROM CustomORDER BY LastName, FirstName I am wondering how to create Update and Insert statements for this SQLServerDataSource since the select is actually driving from two different tables (Master and Custom). Any ideas if or how this can be done? Specifically, I want the Custom table to be editable, but not the Master table. Any examples or ideas would be very much appreciated! Thanks, Randy
View Replies !
&&"(Select All)&&" In Multi-select Enabled Drop Down Parameters Doesn't Work
Hello all, I have two mult-value parameters in my report. Both of them working with selecting one or more values. But, when I test using "(Select All)" values for both parameters , only one parameter works. The "available values" for these two parameters are both from the data set. select distinct ProductType from Product order by ProductType Any suggestion? thx
View Replies !
&&"(Select All)&&" In Multi-select Enabled Drop Down Parameters
There are several parameters on a report. One of the parameter is a multi-select enabled parameter and I suppressed the value "All" showing as one of the item in the drop down list, simply by filter out the [bha].[bha].CURRENTMEMBER.LEVEL.ORDINAL to 1, as "(Select All)" is pre-assigned to the drop list when multi-select is enabled and it is confusing to show "(Select All)" and "All" in the drop list. However I have another report which is linked to this report and the value which is required to pass to this report for this parameter is "All". Can I pass the "Select All" as a parameter from the other report? If so, how? Thanks.
View Replies !
Define Select Parameters
Hi I have a DropDownlist (Drop1) and a GridView,the GridView is bount to an SqlDataSource1 that has 2 Select parameters CatId and SourceId The dropdownlist has a selectedvalue of the following format 15-10(2 numbers seperated by -).I want to set CatId to 15 and SourceId to 10 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Art %>" SelectCommand="Select * from Option Where SourceId=@SourceId And CatId=@CatId"> <SelectParameters> <asp:ControlParameter ControlID="Drop1" Name="SourceId" /> <asp:ControlParameter ControlID="Drop1" Name="CatId" /> </SelectParameters> </asp:SqlDataSource> Can anyone help me to define the parameters? thanks
View Replies !
Select Parameters With Dates
I have a sqlDataSource control that has its select command and parameters set dynamically. One of the parameters is a date, which should be in smalldatetime format (ie, 12/22/2006). Obviously, using SQL Server, the data is stored with both date and time. The problem is, I cannot get any data selected. I initially thought that I needed to tell it to only look at the date and not the time, but from what I have seen this should work. Here is the pertinent code. dim seldate as datetime selDate = Session("ChosenDate") Dim SelCmd As String = "SELECT [PatientName], [AssignedTo], [CPT], [CPT2], [HospitalID], [RoomNbr], [ACType], [TxDx1], [TxDx2], [MRNbr], [Notes], [PatientID], [PCPID], [ResidentID], [Status], [CaseID], [AdmitDate], [crtd_datetime] FROM [DailyBilling] WHERE ([crtd_datetime] = @crtd_datetime) and ([AssignedTo] = @AssignedTo) and ([HospitalID] = @HospitalID) ORDER BY [PatientName]" SqlDataSource1.SelectCommand = SelCmd SqlDataSource1.SelectParameters.Clear() Dim parFilterProvider As New ControlParameter() parFilterProvider.ControlID = "ddlProvider" parFilterProvider.Name = "AssignedTo" parFilterProvider.Type = TypeCode.String SqlDataSource1.SelectParameters.Add(parFilterProvider) Dim parFilterHospital As New ControlParameter() parFilterHospital.ControlID = "ddlHospitals" parFilterHospital.Name = "HospitalID" parFilterHospital.Type = TypeCode.String SqlDataSource1.SelectParameters.Add(parFilterHospital) Dim parFilterStatus As New Parameter() parFilterStatus.Name = "crtd_datetime" parFilterStatus.DefaultValue = selDate.ToShortDateString parFilterStatus.Type = TypeCode.DateTime SqlDataSource1.SelectParameters.Add(parFilterStatus) Gridview1.databind() Any ideas?
View Replies !
Odbc Select Where Parameters
Im enabling an apllication to use ODBC to connect to sqlserver which currently uses Oracle OCI, i have no prior knowledge about odbc use. Im unsure how to approach where clause parameters (bind parameters) ie Oracle OCI select name into :name from emp where name = :a_name via ODBC, connecting to sql server i'm attempting select name from emp where name = ? with, sqlprepare sqlbindparameter sqlexecute sqlbindcol sqlfetch all seems ok with sqlbindparameter, but sqlexecute fails with sqlstate 22001, String data, right truncation. The question: can i use ? parameter in where conditions, if not whats the best approach. Many Thanks.
View Replies !
How To Select (see) Only Parameters Available In The Cube
Hello, I have a report based on a cube with some of the dimensions as parameters filling the drop-down list boxes. What I want to see, or choose from, are only the selections that are available in the particular cube. For example, although I have Managers, Directors and Partners in my dimension, this cube only contains Directors and Managers. How can I make the parameter only contains those two choices? Thank you for the help. -Gumbatman
View Replies !
SSRS Parameters : Select All
In multivalue parameters by default an option "All" was appearing. You can select both "All" and any of the individual parameters. However the latest report I created suddenly appeared with "(Select All)" as well as "All". (Select All) actually selects (or deselects) all items. Does anyone know where (Select All) came from, is this a new thing in SP2? How do you control it. Also, is there a functionality where you can select "All", but if you then select another paramater it automatically deselects "All"? Richard
View Replies !
Select Statment Parameters
I am using an AccessDataSource with this Select statment. SelectCommand="SELECT * WHERE (([Assigned Sponsor] = ?) AND ([Status] = ?)) ORDER BY [FCP Ref N:] DESC" when I use non string parameters it works properly, but the problem that when I use String parameters only the first one pass. Advise please.
View Replies !
Select With From Database With A List Of Parameters
Hi, i have a big problem. I´m having trouble with the select statement in SQL query language. The problem is that I need to retrieve various data from database and the input object is a list. The simple way of doing this is:SELECT <return values>FROM <datatable name>WHERE (<select data parameter>)My problem is that my where parameter needs to be an array list. The simple way of solving the problem would be using a for statement in my c# code and call my store procedure various times, but my array list can be too long and take a long time to connect and search data for each statement, so I need to access the database once.Can anybody help; I would appreciate it very much thx, Malcolm
View Replies !
Select Command Control Parameters
SelectCommand="SELECT [id], [ref_id], [ref_name] FROM [ref] where [delete_flag] = 'N' AND [flag_transmit] = 'N' AND [ref_name] = @ref_name "> <asp:ControlParameter Name="ref_name" ControlId="SrchRefName" PropertyName="Text" ConvertEmptyStringToNull="false"/> The gridview of all the records is displayed on the page by default. There is a lookup of SSN and Name and putting values in those fields should filter the records and display only the row containing entered Name.I have trouble with the SelectCommand. No gridview is displayed with the above command even if value is entered in the Lookup textBox (SrchRefName).But when I change the selectcommand to- (using OR) SelectCommand="SELECT [id], [ref_id], [ref_name] FROM [ref] where [delete_flag] = 'N' AND [flag_transmit] = 'N' OR [ref_name] = @ref_name "> <asp:ControlParameter Name="ref_name" ControlId="SrchRefName" PropertyName="Text" ConvertEmptyStringToNull="false"/> the default gridview is displayed with all the records even though a value is entered in the lookup text box. Please help.
View Replies !
Using Passed Parameters In A Select Statement
hello all, im trying to run a select statement using a parameter, but am having extreme difficulties. I have tried this about 50 different ways but i will only post the most recent cause i think that im the closest now than ever before ! i would love any help i can get !!! Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim pageID As StringpageID = Request.QueryString("ID") TextBox13.Text = pageID 'Test to make sure the value was stored SqlDataSource1.SelectParameters.Add("@pageID", pageID) End Sub .... <asp:SqlDataSource ID="SqlDataSource1" runat="server" ProviderName=System.Data.SqlClient ConnectionString="Data Source=.SQLEXPRESS;Initial Catalog=software;Integrated Security=True;User=something;Password=something" 'SelectCommand="SELECT * FROM Table1 WHERE [ClientID]='@pageID' ></asp:SqlDataSource> The error that i am getting, regardless of what i put inside the ' ' is as follows: "Conversion failed when converting the varchar value '@pageID' to data type int." anyone have any suggestions ?
View Replies !
Output Parameters And Select Statements
Hi, thanks for reading! Here is my problem: I have a strored procedure that inserts some records into one table and then selects some records from another table at the end. The stored procedure takes several parameters, first one of them is marked as OUTPUT. I'm using it to return an id of the inserted record. The procedure is called from asp.net code with first parameter set as ParameterDirection.InputOutput (tried with just Output as well). Now for the problem: if the the select statement at the end returns 0 records everything works and i my first parameter contains the @@IDENTITY value from the insert statement like it is supposed to. If the select statement at the end returns 1 or more records my output parameter is not updated at all and contains the same value as before the procedure was run. All the records are inserted correctly. if i try to return the @@identity as a plain select statement instead of through the parameter i get System.DBNull. I hope you can shed some light on this for me. Here is my stored procedure: CREATE PROCEDURE cwSaveProductInquiry @inquiryId int OUTPUT, @libraryName nvarchar(500), @contactName nvarchar(200), @address nvarchar(100), @city nvarchar(50), @state nvarchar(3), @zip nvarchar(10), @phone nvarchar(50), @email nvarchar(100), @comment nvarchar(3000), @productIds nvarchar(2000) AS INSERT INTO INQUIRY (LibraryName, ContactName, Address, City, State, Zip, Phone, Email, Comment) VALUES(@libraryName, @contactName, @address, @city, @state, @zip, @phone, @email,@comment) --i tried including this statement at the end as well but that did not do the --trick either select @inquiryId=@@IDENTITY FROM INQUIRY set nocount on declare @separator_position int -- This is used to locate each separator character declare @objectId varchar(200) -- this holds each array value as it is returned if(@productIds is not null) begin while patindex('%,%' , @productIds) <> 0 begin select @separator_position = patindex('%,%' , @productIds) select @objectId= left(@productIds, @separator_position - 1) INSERT INTO PRODUCT_INQUIRY_LOOKUP (ProductId,InquiryId) VALUES(@objectId, @inquiryId) select @productIds = stuff(@productIds, 1, @separator_position, '') end end set nocount off Select Distinct Email from vPRODUCT_CONTACT WHERE ProductId in (Select ProductId From Product_Inquiry_Lookup Where InquiryId=@inquiryId) GO
View Replies !
Insert From Parameters And Select Statement
Trying to insert into a history table. Some columns will come fromparameters sent to the store procedure. Other columns will be filledwith a separate select statement. I've tried storing the select returnin a cursor, tried setting the values for each field with a separateselect. Think I've just got the syntax wrong. Here's one of myattempts:use ESBAOffsetsgoif exists(select * from sysobjects where name='InsertOffsetHistory' andtype='P')drop procedure InsertOffsetHistorygocreate procedure dbo.InsertOffsetHistory@RECIDint,@LOB int,@PRODUCT int,@ITEM_DESC varchar(100),@AWARD_DATE datetime,@CONTRACT_VALUE float,@PROG_CONT_STATUS int,@CONTRACT_NUMBER varchar(25),@WA_OD varchar(9),@CURR_OFFSET_OBL float,@DIRECT_OBL float,@INDIRECT_OBL float,@APPROVED_DIRECT float,@APPROVED_INDIRECT float,@CREDITS_INPROC_DIRECT float,@CURR_INPROC_INDIRECT float,@OBLIGATION_REMARKS varchar(5000),@TRANSACTION_DATE datetime,@AUTH_USERvarchar(150),@AUTHUSER_LNAMEvarchar(150)asdeclare@idintinsert into ESBAOffsets..HISTORY(RECID,COID,SITEID,LOB,COUNTRY,PRODUCT,ITEM_DESC,AWARD_DATE,CONTRACT_VALUE,PROG_CONT_STATUS,CONTRACT_TYPE,FUNDING_TYPE,CONTRACT_NUMBER,WA_OD,PM,AGREEMENT_NUMBER,CURR_OFFSET_OBL,DIRECT_OBL,INDIRECT_OBL,APPROVED_DIRECT,APPROVED_INDIRECT,CREDITS_INPROC_DIRECT,CURR_INPROC_INDIRECT,PERF_PERIOD,REQ_COMP_DATE,PERF_MILESTONE,TYPE_PENALTY,PERF_GUARANTEE,PENALTY_RATE,STARTING_PENALTY,PENALTY_EXCEPTION,CORP_GUARANTEE,BANK,RISK,REMARKS,OBLIGATION_REMARKS,MILESTONE_REMARKS,NONSTANDARD_REMARKS,TRANSACTION_DATE,STATUS,AUTH_USER,PMLNAME,EXLD_PROJ,COMPLDATE,AUTHUSER_LNAME)values(@RECID,(Select COID from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select SITEID from ESBAOffsets..Offsets_Master where RECID = @RECID),@LOB,(Select COUNTRY from ESBAOffsets..Offsets_Master where RECID =@RECID),@PRODUCT,@ITEM_DESC,@AWARD_DATE,@CONTRACT_VALUE,@PROG_CONT_STATUS,(Select CONTRACT_TYPE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select FUNDING_TYPE from ESBAOffsets..Offsets_Master where RECID =@RECID),@CONTRACT_NUMBER,@WA_OD,(Select PM from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select AGREEMENT_NUMBER from ESBAOffsets..Offsets_Master where RECID= @RECID),@CURR_OFFSET_OBL,@DIRECT_OBL,@INDIRECT_OBL,@APPROVED_DIRECT,@APPROVED_INDIRECT,@CREDITS_INPROC_DIRECT,@CURR_INPROC_INDIRECT,(Select PERF_PERIOD from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select REQ_COMP_DATE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select PERF_MILESTONE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select TYPE_PENALTY from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select PERF_GUARANTEE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select PENALTY_RATE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select STARTING_PENALTY from ESBAOffsets..Offsets_Master where RECID= @RECID),(Select PENALTY_EXCEPTION from ESBAOffsets..Offsets_Master where RECID= @RECID),(Select CORP_GUARANTEE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select BANK from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select RISK from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select REMARKS from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select OBLIGATION_REMARKS from ESBAOffsets..Offsets_Master whereRECID = @RECID),@MILESTONE_REMARKS,@NONSTANDARD_REMARKS,@TRANSACTION_DATE,(Select STATUS from ESBAOffsets..Offsets_Master where RECID = @RECID),@AUTH_USER,(Select PMLNAME from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select EXLD_PROJ from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select COMPLDATE from ESBAOffsets..Offsets_Master where RECID =@RECID),@AUTHUSER_LNAME)select@@identity idgogrant execute on InsertOffsetHistory to publicgo
View Replies !
Select Into Parameters Grouped Data
Hi all, This is probably one of the easier questions you get, but I have brain freeze and just can't do it and very rusty. How can i assign the the values from sql below into variables e.g I want to get all new, pending and cancelled Leads from the rows returned which will come from the status id. SELECT Count (leadStatusId) As NoOfLeads, leadStatusID, sum(value) As Value FROM [dbo].[tLead] L Inner Join dbo.tLeadStatus S on linkLeadStatus = LeadStatusID Inner Join dbo.tClick C on linkClick = ClickID WHERE L.DateDeleted Is NULL AND linkAffiliateUser = @UserID AND Month(L.DateCreated) = @month And Year (L.DateCreated) = @Year Group by LeadStatusID Order by LeadStatusID asc Cheers
View Replies !
How To Derive Parameters In Ad Hoc SELECT Statements
Hi, If I have ad hoc SQL statements created by users, which could be parameterized, how could I derive the parmeters at runtime. I cannot use CommandBuilder.DeriveParameters() as that is for StoredProcedures only. Just use Split on the SQL string? Or is there a better way, such as a third-party .Net Component? Thanks John
View Replies !
Sqldatasource Using Session Data In Select Parameters
I'm having trouble using session data in my select parameters. If I manually plug a value into the selectcommand or create a hard coded value using a parameter it works, but if I try to use the session data the query pulls no results. I know the session data is set because I print the value at the top of the page, but for some reason it's not getting passed to the sessionparameter??? This is the datasource code: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:flautoconnstr %>" SelectCommand="SELECT * FROM [tblVehicles] WHERE ([profileid] = @profileid)"> <SelectParameters> <asp:SessionParameter Name="profileid" SessionField="profileid" Type="String" /> </SelectParameters> </asp:SqlDataSource> This is the line I use to set the session data. Session["profileid"] = myQuote.Profileid;
View Replies !
Controlling Fields In A Select Statement By Use Of Parameters
Hi to allI wish to be able to have a standard select statement which hasadditional fields added to it at run-time based on suppliedparameter(s).iedeclare @theTest1 nvarchar(10)set @theTest1='TRUE'declare @theTest2 nvarchar(10)set @theTest2='TRUE'selectp_full_nameif @theTest1='TRUE'BEGINother field1,ENDif @theTest2='TRUE'BEGINother field2ENDfrom dbo.tbl_GIS_personwhere record_id < 20I do not wish to use an IF statement to test the parameter for acondition and then repeat the entire select statement particularly asit is a UNIONed query for three different statementiedeclare @theTest1 nvarchar(10)set @theTest1='TRUE'declare @theTest2 nvarchar(10)set @theTest2='TRUE'if @theTest1='TRUE' AND @theTest2='TRUE'BEGINselectp_full_name,other field1,other field2from dbo.tbl_GIS_personwhere record_id < 20ENDif @theTest1='TRUE' AND @theTest2='FALSE'BEGINselectp_full_name,other field1from dbo.tbl_GIS_personwhere record_id < 20END......if @theTest<>'TRUE'BEGINselectp_full_namefrom dbo.tbl_GIS_personwhere record_id < 20ENDMake sense? So the select is standard in the most part but with smallvariations depending on the user's choice. I want to avoid risk ofbreakage by having only one spot that the FROM, JOIN and WHEREstatements need to be defined.The query will end up being used in an XML template query.Any help would be much appreciatedRegardsGIS Analyst
View Replies !
Can You Have Multiple Output Parameters? Difference Between A Select Statement?
I have a user login scenario where I would like to make sure that they not only exist in the user table, but also make sure there account is "verified" and "active". I'm trying to return 3 output parameters. UserID, verified, active. Is this possible? Do I need just a select statement to do this? What is the difference between the output and select statements? Thanks in advance.
View Replies !
Can A Column Be Derived Using Substring But The Parameters Are A Result Of A Select Statement?
I have a table which has a field called Org. This field can be segmented from one to five segments based on a user defined delimiter and user defined segment length. Another table contains one row of data with the user defined delimiter and the start and length of each segment. e.g. Table 1 Org aaa:aaa:aa aaa:aaa:ab aaa:aab:aa Table 2 delim Seg1Start Seg1Len Seg2Start Seg2Len Seg3Start Seg3Len : 1 3 5 3 9 2 My objective is to use SSIS and derive three columns from the one column in Table 1 based on the positions defined in Table 2. Table 2 is a single row table. I thought perhaps I could use the substring function and nest the select statement in place of the parameters in the derived column data flow. I don't seem to be able to get this to work. Any ideas? Can this be done in SSIS? I'd really appreciate any insight that anyone might have. Regards, Bill
View Replies !
SSRS 2005 V SSAS 2000 Mutli-Select Parameters
Has anyone managed to crack getting multi-select parameters to work from an SSRS 2005 report which is querying an SSAS 2000 cube. SSRS 2005 does support Multiselect, however SSRS 2000 did not. Given that i am querying an SSAS 2000 cube, i get the impression that i am also limited to SSRS 2000 functionality regarding to multi-select parameters. Is there anyone out there that ever managed to get a wor around, say by using filters on a table or anything really that coud simulate the same behaviour....
View Replies !
Issues With SQL 2005 SP's. Select/Updates/Remote EXEC Calls With Parameters Fail With No Error. HELP???
I have finally decided to write up my issue because searching forums and Google has been a long waste of time. Has anyone else had a issue where Parms will work in sql script under the SQL server management studio but fail in a stored procedure. I have tried multiple ways for the stored procedure to utilize the parameters by compiling on the fly changing it to dynamic (that seems to work, just does not seem right to add parameters to a string, Adding quotes to execute a external T-SQL command to get results. *** Any thought or resolutions would be greatly appreciated. First Issue regarding a stored procedure select statement within a stored procedure. SELECT *,'Unsolicited' as ttype from ( SELECT Web_Outbound_Uns.ID, Web_Outbound_Uns.PIDID, Web_Outbound_Uns.Port, Web_Uns_Messages.Data, Web_Outbound_Uns.Status, Web_Outbound_Uns.Source, Web_Outbound_Uns.RcvTime FROM Web_Outbound_Uns INNER JOIN Web_Uns_Messages ON Web_Outbound_Uns.Seq_ID = Web_Uns_Messages.Seq_ID WHERE (Web_Outbound_Uns.PIDID = @ID) ) z WHERE STATUS='1' ORDER BY RCVTIME Full stored procedure on bottom of page. I have a variable @ID that, I want to use as a my search parameter. The funny thing is this will fail to work within my stored procedure. If, I set this parameter as hard coded '99 99 99 79' boom it works with out a hitch. Yes, I have tried using exec, and sqlcmd but this is the tip of the ice berg from hundreds of SP's. If, I take this script into a query editor and execute by hard coding the expected stored procedure input values, boom it works. Issue two remote SQL 2000 stored procedure call. Set @query = N'[APSQL].[Alerts].[dbo].[ProcessForcedByeCommand] ' Set @query = @query + '''' + @PID + '''' exec (@query) Again the above coded worked to accept parameters and execute the remote stored procedure. But the orginal code statement was; EXEC [APSQL].[Alerts].[dbo].[ProcessForcedByeCommand] @PID This Exec does not return a error. It just does nothing during a trace from both severs nothing is sent to remote sql2000. Change this exec where the @PID parameter is hardcoded. and it will work in a stored procedure. I have a few more dealing with Update with a index not executiong with a parameter also. Hard code the param and it works. No errors once again with any code. ALTER PROCEDURE [dbo].[Alecs_Get_All_Messages] @DeptID varchar(6), @UserName varchar(30) AS -- New System will use @UserName with '~' at begin to denote a true pidid passed in DECLARE @ID varchar(15) DECLARE @ViewCount int BEGIN TRY if substring(@UserName, 1, 1) = '~' begin set @ID = replace(@UserName, '~', '') end else begin SELECT TOP 1 @ID = [PIDID] from APSQL.Alerts.dbo.session WHERE DeptIDNow = @DeptID AND UserName = @UserName AND len(PIDID) < 8 end select *, 'Alecs/Leads' as ttype from Alecs_Web_Messages.dbo.[web_outbound] where pidid = @ID UNION ALL select *, 'Local Message' as ttype from Alecs_Web_Messages.dbo.[Web_Outbound_LocalMessages] where pidid = @ID UNION ALL SELECT *,'Unsolicited' as ttype from ( SELECT Web_Outbound_Uns.ID, Web_Outbound_Uns.PIDID, Web_Outbound_Uns.Port, Web_Uns_Messages.Data, Web_Outbound_Uns.Status, Web_Outbound_Uns.Source, Web_Outbound_Uns.RcvTime FROM Web_Outbound_Uns INNER JOIN Web_Uns_Messages ON Web_Outbound_Uns.Seq_ID = Web_Uns_Messages.Seq_ID WHERE (Web_Outbound_Uns.PIDID = @ID) ) z WHERE STATUS='1' ORDER BY RCVTIME END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage END CATCH
View Replies !
Need Help W/ Postback To 'Customers' Table On Form Using Select Query From 'Parameters' Table
I have set up a 'Parameters' table that solely stores all pre-assigned selection values for a webform. I customized a stored query to Select the values from the Parameters table. I set up the webform. The result is that the form1.apsx automatically populates each DropDownList task with the pre-assigned values from the 'Parameters' table (for example, the stored values in the 'Parameters' table 'Home', 'Business', and 'Other' populate the drop down list for 'Type'). The programming to move the selected data from form1.aspx to a new table in the SQL database perplexes me. If possible, I would like to use the form1.aspx to Postback (or Insert) the "selected" data to a *new* column in a *new* table (such as writing the data to the 'CustomerType' column in the 'Customers' table; I clearly do not want to write back to the 'Parameters' table). Any help to get over this hurdle would be deeply appreciated.
View Replies !
Execute &&"Select&&" Depending On The Input Parameters
Hello, a question please. Could anyone say me if I can create a store procedure with 2 'select's statements into. Besides, I'd want to know if I can execute a "select" depending on input parameters. Something like this: create storeproc Param1, param2 if param1 <> null Select * from table where id = param1 else Select * from table where id = param2 end if Thanks in advance....
View Replies !
Problem With &&"select All&&" On 2 Multi-value Cascading Parameters
Hello, since some hours I'm struggling with 2 multi-value cascading parameters which default values should be always "Select ALL" First Parameter: available vlaues: From query dataSetsGetCountry (defined as select from tblCountries) ValueFied:ContryName LabelField:CountryName DefaultValues: from Query dataSetsGetCountry ValueFied:ContryName SecondParameter: available vlaues: From query dataSetsGetAreas (stored procedure which parameter is the list of the selected countries) ValueFied:AreaName LabelField:AreaName DefaultValues: from Query dataSetsGetAreas ValueFied:AreaName First time I open the report the first and the second parameters are properly filled and for both parameters "select all" is checked. I select one option from the first parameter, the second parameter's content change dinamically and "Select All" option is still selected !Cool Now I change the selection on the first Parameter, by checking AN ANOTHER item from the list , the second parameter list refresh dinamically but "Select all" IS NOT selected and only the item that were previously checked kept the selection !!!NO!! Is this a bug in Reporting services and I have to say to ther user that is not possible to develop what they would like to have or there is , even programmatically, a way to solve it? Thankx for any helps! Marina B
View Replies !
Two Report Parameters: &&"Please Select A Value For The Parameter....&&"
I´ve build a report with Report Design. On this report I want to show the items customers bought. In this report I added a Report Parameter so the user can select a specific customer. I made an extra dataset and use the filter =@customer and this parameter works fine. Then I want to ad a second Report Parameter: the salesperson. When I leave one of the parameters blank, I get an error "Please select a value for the parameter....". Even if I choose the options allow blank or null values, I get this error. What I want is de possibility to get all the records, to filter records from one specific customer or to filter records from a specific salesperson.
View Replies !
ADO.NET 2-VB 2005 Express Form1:Printing Output Of Returned Data/Parameters From The Parameters Collection Of A Stored Procedure
Hi all, From the "How to Call a Parameterized Stored Procedure by Using ADO.NET and Visual Basic.NET" in http://support.microsft.com/kb/308049, I copied the following code to a project "pubsTestProc1.vb" of my VB 2005 Express Windows Application: Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlDbType Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim PubsConn As SqlConnection = New SqlConnection("Data Source=.SQLEXPRESS;integrated security=sspi;" & "initial Catalog=pubs;") Dim testCMD As SqlCommand = New SqlCommand("TestProcedure", PubsConn) testCMD.CommandType = CommandType.StoredProcedure Dim RetValue As SqlParameter = testCMD.Parameters.Add("RetValue", SqlDbType.Int) RetValue.Direction = ParameterDirection.ReturnValue Dim auIDIN As SqlParameter = testCMD.Parameters.Add("@au_idIN", SqlDbType.VarChar, 11) auIDIN.Direction = ParameterDirection.Input Dim NumTitles As SqlParameter = testCMD.Parameters.Add("@numtitlesout", SqlDbType.Int) NumTitles.Direction = ParameterDirection.Output auIDIN.Value = "213-46-8915" PubsConn.Open() Dim myReader As SqlDataReader = testCMD.ExecuteReader() Console.WriteLine("Book Titles for this Author:") Do While myReader.Read Console.WriteLine("{0}", myReader.GetString(2)) Loop myReader.Close() Console.WriteLine("Return Value: " & (RetValue.Value)) Console.WriteLine("Number of Records: " & (NumTitles.Value)) End Sub End Class ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// The original article uses the code statements in pink for the Console Applcation of VB.NET. I do not know how to print out the output of ("Book Titles for this Author:"), ("{0}", myReader.GetString(2)), ("Return Value: " & (RetValue.Value)) and ("Number of Records: " & (NumTitles.Value)) in the Windows Application Form1 of my VB 2005 Express. Please help and advise. Thanks in advance, Scott Chang
View Replies !
Gridview
Hi I have a business search box and gridview pair. When the user enters a business name, the search results are displayed. I also generate a "more information" link which takes the user to a new page, passing the business name ("memberId")to this page (see the template field below). The problem I have is if the name contains a QUOTE (') or other special characters. The "memberId" is chopped off at the quote (e.g. "Harry's Store" is passed as "Harry"). Can anyone tell me a way around this please? Is there anything I can do with the Eval method? Kind regards, Garrett <asp:TemplateField HeaderText="More Info"> <ItemTemplate> <a href='member_page.aspx?memberId=<%# Eval("co_name") %>'>more</a> </ItemTemplate> <ItemStyle Font-Bold="False" /> </asp:TemplateField>
View Replies !
???GridView
HiI need to add in gridview control asp code "delete from t1 where id=@id1"how to declare @id1 because the server give me mistake down is the code of asp i use GridView how i can link @id with field there id???Thank u and have a nice daybest regardsthe code if u need it i use c# <ASP:SQLDATASOURCE id=SqlDataSource1 <br ConnectionString="<%$ ConnectionStrings:libraryConnectionString %>" runat="server"><BR></ASP:SQLDATASOURCE></ASP:BOUNDFIELD>
View Replies !
GridView Help
Hi, I use WVD and SQL Express 2005. I have a table “SignIn� that one of fields inserted automatically by getdate() And I have GridView that I use to display this table because I would like take advantage of GridView sorting and paging methods that are embedded in. Currently I display all records at once. My problem is how to make the GridView show today’s records only. I tried this code below, but I get only this message “There are no data records to display.� <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RC1 %>" ProviderName="<%$ ConnectionStrings:RC1.ProviderName %>" SelectCommand="SELECT [student_ID], [SignIn], [SignOut], [Location] FROM [Stud_data] WHERE (CONVERT(VARCHAR(10),[SignIn],101) = @SignIn)"> <SelectParameters> <asp:QueryStringParameter Name="SignIn" QueryStringField="Format(Now, "M/dd/yyyy")" Type="DateTime" /> </SelectParameters> </asp:SqlDataSource> Help Please!
View Replies !
Gridview And Sqldatasource
i have a gridview which is bound to sqldatasource. i have a delete button in the gridview. I have written code for "deleting" a record in app_code directory. now iam not using "deletecommand" of sqldatasource but on the click of "delete" link i want to call the procedure in the app_code. Any ideas on how to do it.??
View Replies !
Help!!! Gridview Binding
Hey guys, Am in need of help please, basically the program im working with at the moment is when you add a New Contract, it will grab the Contract Number you have entered, Post it over to another page, then using that number bind a Gridview. The SQL being "SELECT Contract_ID, Contract_Number, Start_Date, End_Date, Quarterly_Rent FROM ECS_Contracts_Test WHERE Contract_Number = " & conNoVar (this being the Contract Number of the recently added Contract), however then it comes to Bind the Grid it kicks up an System.Data.SqlClient.SqlException: Syntax error converting the nvarchar value '2009P7899' to a column of data type int.But the Column Contract_Number is set to Varchar and all I really want to do is to create this gridview using this criteria and not convert anything! The Contract_ID is an int, which is needed as I increment it. Heres the error code: Public Sub BindtheGrid()'Bind the Contract Grid, where ContractID is used Dim SQL As String = "Contract_ID, Contract_Number, Start_Date, End_Date, Quarterly_Rent" Dim objConn As SqlConnection = New SqlConnection(ConnectionString) Dim cmdstock As SqlCommand = New SqlCommand("SELECT " & SQL & " FROM ECS_Contracts_Test WHERE Contract_Number = " & contractQueryID, objConn) cmdstock.CommandType = CommandType.Text objConn.Open() GridView1.DataSource = cmdstock.ExecuteReader() GridView1.DataBind() objConn.Close() End Sub If you need any more information then please let me know. Mucho Aprreciated
View Replies !
Gridview Sql Timeout
I have a simple gridview displaying data from an MSSQL server 2005. Every now and then I get a sql timeout error. Listed below. Can anyone explain why I am getting this error? The connection pool is 100 and the timeout is set to 360. I have checked to current connections in SQL and they never max over 23. There are not locks in SQL when the problem occurs. The query is a stored procedure in sql and when sent sample data it normally takes about 5 seconds. Event code: 3005 Event message: An unhandled exception has occurred. Event time: 12/3/2007 9:46:37 PM Event time (UTC): 12/4/2007 3:46:37 AM Event ID: 140501f9a7744dfea2e445ed00939e44 Event sequence: 42 Event occurrence: 1 Event detail code: 0 Application information: Application domain: /LM/W3SVC/1/ROOT-1-128412128787656250 Trust level: Full Application Virtual Path: / Application Path: c:inetpubwwwroot Machine name: DD-MAIN Process information: Process ID: 5544 Process name: w3wp.exe Account name: NT AUTHORITYNETWORK SERVICE Exception information: Exception type: SqlException Exception message: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Request information: Request URL: http://localhost/Search_DG.aspx?SearchWord=1212 Request path: /Search_DG.aspx User host address: 10.10.10.1 User: Is authenticated: False Authentication Type: Thread account name: NT AUTHORITYNETWORK SERVICE Thread information: Thread ID: 1 Thread account name: NT AUTHORITYNETWORK SERVICE Is impersonating: False Stack trace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.SetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.GridView.DataBind() at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() at System.Web.UI.Control.EnsureChildControls() at System.Web.UI.WebControls.GridView.get_Rows() at Install_DG.Page_Load(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) Custom event details: For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
View Replies !
SQL OutputCache GridView
I'm trying to cache the contents of a gridivew unless another page, or sorting method are being called. I tried to use the VaryByParam method, but I'm not having any luck, I keep getting the same page sent back to me. Here's what my code looks like. <%@ OutputCache Duration="180" VaryByParam="Page$, Sort$" %> Any help would be appreciated. Stephen
View Replies !
Gridview Question
Sqldatasources are used for a dropdownlist and a gridview. How can the dropdownlist selection refresh the gridview? This is done programmatically in ASP.NET 1.1 code behind. Can it be done in ASP.NET 2.0 without code behind? Thanks.
View Replies !
|