SqlDataSource And SSMSE Returning Different Results For Same SELECT Command

Oct 2, 2007

Hi,

Hope you guys won't mind this rather newbie question.  I'm writing a simple blog page for my website and have created a SqlDataSource which queries the database for a list of blog post titles (from the web.Blog table) and the number of comments (from the web.BlogComments table).  The SqlDataSource control is:

<asp:SqlDataSource ID="sourceBlogArticles" ProviderName="System.Data.SqlClient" connectionString="<%$ ConnectionStrings:myDatabase %>" runat="server" SelectCommand="SELECT gb.blogID, gb.title, gb.description, gb.tags, gb.dateAdded, COUNT(gbc.blogID) AS noOfComments FROM web.Blog gb LEFT OUTER JOIN web.BlogComments gbc ON gb.blogID = gbc.blogID GROUP BY gb.blogID, gb.title, gb.description, gb.tags, gb.dateAdded ORDER BY gb.dateAdded"></asp:SqlDataSource>

This works perfectly well if each blog entry in the web.Blog table has associated comments in the web.BlogComments table.  However, if there are no comments yet defined in the web.BlogComments table for that blogID then no row is returned in ASP.Net (as checked with a GridView control or similar linked to the data source to view what I get)

 HOWEVER, I think the SELECT command IS correct: if I use the select command as a query in SQL Server Managment Studio Express, I do get the rows returned, with 0 for the number of comments which is what I would expect for that query:

blogID, title, description, tags, dateAdded, noOfComments

1, title 1, description for title 1, tag1, 2007-09-27 06:49:03.810, 3
2, title 2, description for title 2, tag2, 2007-09-27 06:49:37.513, 0
3, title 3, description for title3, tag3, 2007-10-02 18:21:30.467, 0

Can anyone help?  The result from the SSMSE query is what I want, yet when I use the very same SELECT statement in my SqlDataSource I don't get any rows returned if the BlogComment count is zero (in the above example I get only the first row).  Many thanks for any suggestions!

View 6 Replies


ADVERTISEMENT

ASP: SqlDataSource - Select Command

Aug 10, 2007

I am using  <asp:SqlDataSource ID and for the Select Command, the following, where the WHERE clause ... for an exact match (=) works correctly:
SelectCommand="SELECT [PatientID], [MedRecord] , [Accession], [FirstName], [LastName], [Address1] FROM [ClinicalPatient] WHERE (LastName = @LastName) ORDER BY [LastName]DESC">
 I would like to do a "LIKE" search where the LastName Parameter is matched using "LIKE".  In  this situation how would the syntax be written.... I tried:
LastName LIKE '%" & LastName & "%'"
But I get an error???? Any suggestions, please...
Thanks !!

View 4 Replies View Related

SqlDataSource Select Command

Nov 15, 2007

I have a SqlDataSource object that is bound to a GridView control. I have configured the SqlDataSource with a default select command. Under certain values of query strings on the URL for this page (Default.aspx), I want to change the select command. So I put the statements in the Page_Load method for Default.aspx to define SqlDataSource1.SelectCommand. The changed SelectCommand works fine for the first page of GridView data and shows 5 GridView pages, but if I switch to one of the other pages, it seems to revert to the default SelectCommand (which generates 19 GridView pages). I assume I should put my code to change the SelectCommand somewhere else. Can someone help me with where to put it? Thanks!

View 1 Replies View Related

Select Script Returning Different Results When Used In A Stored Procedure.

Nov 20, 2007



I have a script with a number of different Left Joins. When I run it in Query Analyzer the Left Join works as a normal join and suppresses some rows. However when the same code is used in a stored procedure the correct results are produced when the stored procedure is executed.
Can anyone tell me what is causing this?


SELECT USR.ROLEUSER
,PER.NAME
,EMP.PAYGROUP
,USR.ROLENAME
,OPR.EMPLID
,OPR.OPRDEFNDESC
,OPR.ACCTLOCK
,OPR.ROWSECCLASS
,EMP.JOBCODE
,JCD.DESCR
,EMP.DEPTID
,EMP.DEPTNAME


FROM PSROLEUSER USR
JOIN
PSOPRDEFN OPR
ON
USR.ROLEUSER = OPR.OPRID

LEFT OUTER JOIN
PS_PERSONAL_DATA PER
ON
OPR.EMPLID = PER.EMPLID

LEFT OUTER JOIN
PS_EMPLOYEES EMP
ON
OPR.EMPLID = EMP.EMPLID


LEFT OUTER JOIN
PS_JOBCODE_TBL JCD
ON
JCD.SETID = 'RBLTT'
AND EMP.JOBCODE = JCD.JOBCODE
AND JCD.EFFDT =
(SELECT MAX(EFFDT)
FROM PS_JOBCODE_TBL
WHERE JCD.SETID = SETID
AND JCD.JOBCODE = JOBCODE
AND EFFDT <= GETDATE())

WHERE OPR.ACCTLOCK = 0
AND USR.ROLENAME = 'RBL MANAGER'

AND EMP.PAYGROUP NOT IN ('RBA', 'RMA')

View 2 Replies View Related

SqlDataSource.Select Command Not Working?

May 26, 2007

My compiler says that the line in bold below is illegal. The error msg I'm getting is: No overload for method 'select' takes '0' arguments. How can I correct this error and execute a SELECT?
 protected void Button1_Click(object sender, EventArgs e)
{
SqlDataSource2.Select ();
 }
 protected void SqlDataSource2_Selected(object sender, SqlDataSourceStatusEventArgs e)
{string strReadyFirstName = e.Command.Parameters["@FirstName"].Value.ToString();string strReadyLastName = e.Command.Parameters["@LastName"].Value.ToString();
}
 <asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [User_ID], [User_Name], [FirstName], [LastName], [Company_Name], [Department_Name] FROM [CompanyDepartment] WHERE ([User_Name] = @User_Name)" OnSelected="SqlDataSource2_Selected">
<selectparameters>
<asp:sessionparameter DefaultValue="TheirUserName" Name="User_Name" SessionField="TheirUserName" Type="String" />
</selectparameters>
</asp:SqlDataSource>

View 1 Replies View Related

Dynamic SELECT Command In SqlDataSource

Jul 20, 2007

I have a GridView (that uses SqlDataSource1) and a Dropdownlist.  Depending upon the value selected on the DropDownList I need to select different stored procedures for the gridview.  The problem is that I can do it without taking SqlDataSource1 by using DataSet or DataTable.  But, I need to Use SQLDataSource1 for easy way of Header SORTING.  So, is there any way to change the SQLDatasource1.SELECT Command dynamically. So that, I can use different queries for the Single DataGrid. I have attached the sample code of the SqlDataSource1 I'm using.  I need to change the Command i.e. SelectCommand="usp_reports_shortages" to "usp_reports_shortagesbyID" and "usp_reports_shortagesbyDate"     depending on the value selected in the dropdownlist.  So, is there any way to do this????<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="<%$
ConnectionStrings:TESTDrivercommunication %>"


    SelectCommand="usp_reports_shortages" SelectCommandType="StoredProcedure">


    <SelectParameters>


        <asp:ControlParameter ControlID="lblDriver" Name="date1" PropertyName="Text" Type="DateTime" />


        <asp:ControlParameter ControlID="lblTODate" Name="date2" PropertyName="Text" Type="DateTime" />


        <asp:ControlParameter ControlID="DDlDriver" Name="driver" PropertyName="SelectedValue"


            Type="Int32" />


        <asp:SessionParameter Name="week" SessionField="s_week" Type="DateTime" />


    </SelectParameters>


</asp:SqlDataSource>

View 1 Replies View Related

Dynamic SqlDataSource Select Command?

Apr 25, 2008

I am trying to implement an "advanced search" feature on my ASP.NET 2.0 web form.  I have a GridView control and a SqlDataSource.  The SqlDataSource control successfully retrieves data when the SelectCommand attribute is set in the aspx page.  I need to make it so when a user clicks on a button, it can take a value from a text box and use it in the WHERE clause.  I have tried setting the SelectCommand programmatically and then DataBinding but it never accepts the new SelectCommand. What can I do to fix this?

View 5 Replies View Related

T-SQL (SS2K8) :: Prevent SELECT Query From Returning Results Using LOCKS

Dec 2, 2014

I am trying to find a way to lock rows of data used in a SELECT query from being read by another SELECT query.

I could do a "begin tran - select - update - rollback" sequence but was wondering if there is a cleaner way to do this??

Tried UPDLOCK, ROWLOCK, TABLOCK, HOLDLOCK in multiple variations but none seem to block the select.

View 9 Replies View Related

SQLDatasource With Multiple Controlparameters For Select Command

Sep 1, 2006

I would like to introduce myself as ASP.Net 2.0 beginner. I face a problem when using gridview and sqldatasource.

View 1 Replies View Related

SQL Server 2008 :: Elegant Way For Returning All Results When Subquery Returns No Results?

Mar 25, 2015

I have four tables: Customer (CustomerId INT, CountyId INT), County (CountyId INT), Search(SearchId INT), and SearchCriteria (SearchCriteriaId INT, SearchId INT, CountyId INT, [others not related to this]).

I want to search Customer based off of the Search record, which could have multiple SearchCriteria records. However, if there aren't any SearchCriteria records with CountyId populated for a given Search, I want it to assume to get all Customer records, regardless of CountyId.

Right now, I'm doing it this way.

DECLARE @SearchId INT = 100
SELECT * FROM Customer WHERE
CountyId IN
(
SELECT CASE WHEN EXISTS(SELECT CountyId FROM SearchCriteria WHERE SearchId = @SearchId)
THEN SearchCriteria.CountyId

[Code] .....

This works; it just seems cludgy. Is there a more elegant way to do this?

View 4 Replies View Related

SQL Server Management Studio Express (SSMSE)=&&>Object Explorer=&&>Databases Has C:SSMSE-BookChapter12WINCH12NORTHWND.MDF?

Feb 27, 2008

Hi all,

In my SQL Server Management Studio Express (SSMSE)=>Object Explorer=>Databases, the "NORTHWND" database was screwed up and is deleted completely. But under the same Object Explorer =>Databases, there is a database "C:SSMSE-BookChapter12WINCH12NORTHWND.MDF". I need to use this "NORTHWND" database in the SqlConnection. How can I specify the "Initial Catalog" (or "database") in the New SqlConnection code statement (in the ADO.NET 2.0-VB 2005 Express programming)?
Should it be like the following:

Dim sqlConnection As SqlConnection = New SqlConnction("Data Source=.SQLEXPRESS; Initial Catalog=C:SSMSE-BookChapter12WINCH12NORTHWND; Integrated Security=SSPI;") ? Or what is the right code statement for connecting to it?

Please help and advise.

Thanks in advance,
Scott Chang

View 7 Replies View Related

Returning Identity With SQLDataSource

Mar 25, 2008

Hello all,I have a sqldatasource that inserts data to the database but I want to get the ID from an Identity field after I am done inserting the data.  How can I best do that?  I'm not using a stored procedure to do this.  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:onepduConnectionString %>"          InsertCommand="INSERT INTO [tblaccounts] ([fname],[lname], [address], [city], [state], [zip], ,[phone],[credits]) VALUES (@fName,@lname, @address, @city, @state, @zip, @email, @phone, @credits)>                                    <InsertParameters>                <asp:FormParameter Name="fname" FormField="FirstNameTextBox" Type="String" />                <asp:FormParameter Name="lname" FormField="LastNameTextBox" Type="String" />                <asp:FormParameter Name="address" FormField="AddressTextBox" Type="String" />                <asp:FormParameter FormField="cityTextBox" Name="city" Type="String" />                <asp:FormParameter FormField="stateTextBox" Name="state" Type="String" />                <asp:FormParameter FormField="zipTextBox" Name="zip" Type="String" />                <asp:FormParameter FormField="emailTextBox" Name="email" Type="string" />                <asp:FormParameter FormField="phoneTextBox" Name="phone" Type="string" />                <asp:Parameter Name="credits" DefaultValue=0 />                                           </InsertParameters>        </asp:SqlDataSource> 

View 2 Replies View Related

Programmatic Use Of SQLDataSource Not Returning Dataview

Sep 4, 2007

I am creating an ad-hoc reporting module for my website.  The user may select a list of columns and specify the WHERE for the report.  I build the select statement and the where statement and pass the info to a stored procedure.  The stored procedure accepts 3 select parameters and a 3 wherestmt parameters.  I finally got the SQLDatasource to work by setting the parameter values in the Selecting method of the SQLDatasource.  Binding it to a gridview shows me all my values.  Now, I am trying to programmatically call the select method of the SQLDatasource so I can get a dataview or datareader to manipulate further.  I am getting an null back when I call the select method.  Any ideas why? or a workaround?
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AssetMgmtRWConnectionString %>"SelectCommand="getAdhocRptData" SelectCommandType="StoredProcedure" DataSourceMode="DataReader">
<SelectParameters>
<asp:Parameter Name="strSelect" Type="String" />
<asp:Parameter Name="strSelect2" Type="String" />
<asp:Parameter Name="strSelect3" Type="String" />
<asp:Parameter Name="strWhere" Type="String" />
<asp:Parameter Name="strWhere2" Type="String" />
<asp:Parameter Name="strWhere3" Type="String" />
<asp:Parameter Name="bitDebug" Type="Boolean" />
</SelectParameters>
</asp:SqlDataSource>
 
<VB Code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Getting an error that the object is null? why is the above code not returning any data?
'Tried using a datareader and datasource.Dim rptview As IDataReader = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), IDataReader)
If rptview.Read Then
lblMsg.Text = "Got Rows"
End If
End Sub
Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
'For this sp, need to set each paramater even if it is not being used. Setting it in the wizard
'does not work. Need to be set programmatically.
e.Command.Parameters("@strSelect").Value = "p.field1, p.field2 "
e.Command.Parameters("@strSelect2").Value = "s.field1, s.field2"
e.Command.Parameters("@strSelect3").Value = "a.field1, a.field2, a.field4, a.field5"
e.Command.Parameters("@strWhere").Value = "p.field3 is not null and a.field5 is null"
e.Command.Parameters("@strWhere2").Value = "'"
e.Command.Parameters("@strWhere").Value = ""
e.Command.Parameters("@bitdebug").Value = False
End Sub
 
thanks for any help.
 

View 2 Replies View Related

Returning Amount Of Rows From Sqldatasource

Oct 10, 2007

TotalSelected.Value = SqlDataSource1.SelectCommand = "SELECT COUNT(*) FROM tblNews";
 
the reason i am tring to do this is so if i can find out the amount of rows before sqldatasource selects for details view then i can make the sqldataesource select depends on total minus 5 so e.g. if total 200 then - 5 so i can select bottom 195 so it misses top 5 for details view any1 any ideas?
 Thanks Andy,

View 5 Replies View Related

SQLDataSource.Update Returning Negative Value

Jun 9, 2008

Does anyone know why would SQLDataSource.Update method return a negative value even though its updating records correctly?Its happening with .NET 2.0. 

View 2 Replies View Related

SELECT A Single Row With One SqlDataSource, Then INSERT One Of The Fields Into Another SqlDataSource

Jul 23, 2007

What is the C# code I use to do this?
I'm guessing it should be fairly simple, as there is only one row selected. I just need to pull out a specific field from that row and then insert that value into a different SqlDataSource.

View 7 Replies View Related

Returning No Results

May 19, 2008

I have the following stored procedure that is returning nothing can anyone please help?
 SELECT     job_id, line_num, cust_id, cust_po_id, product_desc, form_num, revision, flat_size, new_art_reprint, order_qty, po_recieved_date, ord_ent_date,                       customer_due_date, scheduled_ship_date, act_ship_date, act_ship_qty, ship_from, ship_to, price_per_m, misc_charges, commentsFROM         tblOrderWHERE     (cust_id = @Cust_Id) AND (po_recieved_date BETWEEN @Start AND @End)
 When I input parameters I make sure my start date is before the first po_recieved_date and the end date is after it yet it is returning nothing. I also made sure that I am putting the correct @Cust_Id

View 6 Replies View Related

Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE

Feb 23, 2007

i am using visual web developer 2005 and SQL 2005 with VB as the code behindi am using INSERT command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString()        test.InsertCommandType = SqlDataSourceCommandType.Text        test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) "                  test.InsertParameters.Add("roll", TextBox1.Text)        test.InsertParameters.Add("name", TextBox2.Text)        test.InsertParameters.Add("age", TextBox3.Text)        test.InsertParameters.Add("email", TextBox4.Text)        test.Insert() i am using UPDATE command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()        test.UpdateCommandType = SqlDataSourceCommandType.Text        test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll                                                         123 "        test.Update()but i have to use the SELECT command like this which is completely different from INSERT and  UPDATE commands   Dim tblData As New Data.DataTable()         Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated                                                                                Security=True;User Instance=True")   Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn)   Dim da As New Data.SqlClient.SqlDataAdapter(Command)   da.Fill(tblData)   conn.Close()                   TextBox4.Text = tblData.Rows(1).Item("name").ToString()        TextBox5.Text = tblData.Rows(1).Item("age").ToString()        TextBox6.Text = tblData.Rows(1).Item("email").ToString()       for INSERT and UPDATE commands defining the command,commandtype and connectionstring is samebut for the SELECT command it is completely different. why ?can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?if its possible how to do ?please help me

View 2 Replies View Related

Results Are Returning On Different Row Levels?

Feb 26, 2014

How do I get my data to show starting at the first row instead of skipping down?

Refer to the attachment.

Code:
CREATE PROCEDURE [dbo].[uspReportData]
-- Add the parameters for the stored procedure here
@Metric1 as varchar(50) = NULL, @Metric2 as varchar(50) = NULL, @Metric3 as varchar(50) = NULL, @Metric4 as varchar(50) = NULL,
@Metric5 as varchar(50) = NULL, @Metric6 as varchar(50) = NULL, @Metric7 as varchar(50) = NULL, @Metric8 as varchar(50) = NULL,

[code].....

View 1 Replies View Related

SQL Command Returning Some Incorrect Records

Nov 13, 2006

I am fairly sure that I am just overlooking something, but the following command is returning some incorrect fields. 
SqlDataSource1.SelectCommand = "SELECT ITNBR, (SELECT ITDSC FROM AMFLIBT.ITEMASA WHERE AMFLIBT.ITEMASA.ITNBR = AMFLIBT.ITEMBL.ITNBR) AS ITDSC, SUM(MOHTQ) AS Balance, (SELECT VNDNR FROM AMFLIBT.ITEMASA WHERE AMFLIBT.ITEMASA.ITNBR = AMFLIBT.ITEMBL.ITNBR) AS VENDOR FROM AMFLIBT.ITEMBL WHERE VNDNR = @DDLVNDNR GROUP BY ITNBR, VENDOR"
SqlDataSource1.SelectParameters.Add("ddlvndnr", ddl1.SelectedValue)
I have more code to show, if this looks correct.  Just let me know.
Thanks in advance.

View 2 Replies View Related

If Exists Command Returning An Error

Feb 24, 2007

Hello, can anyone see a problem with this T-SQL? 1 set ANSI_NULLS ON
2 set QUOTED_IDENTIFIER ON
3 GO
4 ALTER PROCEDURE [dbo].[Logon_P]
5 @User_ID VARCHAR(50),
6 @User_Password VARCHAR(50)
7 AS
8
9 IF EXISTS(SELECT 1
10 FROM [User]
11 WHERE [User_Name] = @User_ID)
12 BEGIN
13 RETURN 1
14 IF ((SELECT User_Password FROM dbo.[User] WHERE [User_Name]) = @User_ID) = @User_Password
15 BEGIN
16 RETURN 2
17 END
18 END
19 ELSE
20 RETURN 0
21 Its returning the following error:Msg 4145, Level 15, State 1, Procedure Logon_P, Line 11An expression of non-boolean type specified in a context where a condition is expected, near ')'. 

View 3 Replies View Related

SQLdatasource Wired To A Stored Procedure Not Returning Records.

Dec 9, 2005

Hi, and thanks in advance.
I have VWD 2005 Express and SQL 2005 Express running.
I have a SqlDastasource wired to the stored procedure. When I only include one Control parameter I get results from my Stored procedure, when I inclube both Control Parameters I get no results. I manually remove the second control parameter from the sqldatasource by deleting...
<asp:ControlParameter ControlID="ddlSClosed" DefaultValue="" Name="SClosed" PropertyName="SelectedValue" Type="String" />
I have one Radio Group and one dropdownlist box that supplies the parameters. The dropdownlist parameter is Null or "" when the page is first loaded.
Below is my SQLDatasource and Stored procedure. I am new to Stored Procedures, so be gentle.
Any help would be appreciated!
 
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Data for DatabaseSQLConnectionString %>"
ProviderName="<%$ ConnectionStrings:Data for DatabaseSQLConnectionString.ProviderName %>"
SelectCommand="spDisplayServiceOrders" SelectCommandType="StoredProcedure" OnSelecting="SqlDataSource1_Selecting" EnableCaching="True" cacheduration="300" OnSelected="SqlDataSource1_Selected">
<SelectParameters>
<asp:ControlParameter ControlID="RadioButtonList1" ConvertEmptyStringToNull="False"
DefaultValue="2005-11-1" Name="SDate_Entered" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="ddlSClosed" DefaultValue="" Name="SClosed" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
 
 
ALTER PROCEDURE [dbo].[spDisplayServiceOrders]
(
@SDate_Entered SmallDateTime,
@SClosed nvarchar(50)= NULL
)
AS
If @SClosed IS NULL
BEGIN

SELECT Service_Orders.SStore_Assigned_Number, Store_Info.Store_Other, Service_Orders.PO_Number, Service_Orders.SWorkType, Service_Orders.Service_Order_Number, Service_Orders.SDate_Entered, Service_Orders.SContact, Service_Orders.SClosed FROM Service_Orders INNER JOIN Store_Info ON Service_Orders.Store_ID = Store_Info.Store_ID
and SDate_Entered >= @SDate_Entered
Order by SDate_Entered DESC
END
ELSE
BEGIN

SELECT Service_Orders.SStore_Assigned_Number, Store_Info.Store_Other, Service_Orders.PO_Number, Service_Orders.SWorkType, Service_Orders.Service_Order_Number, Service_Orders.SDate_Entered, Service_Orders.SContact, Service_Orders.SClosed FROM Service_Orders INNER JOIN Store_Info ON Service_Orders.Store_ID = Store_Info.Store_ID
and SDate_Entered >= @SDate_Entered
and SClosed = @SClosed
Order by SDate_Entered DESC

END

View 2 Replies View Related

Is There A Way To Hold The Results Of A Select Query Then Operate On The Results And Changes Will Be Reflected On The Actual Data?

Apr 1, 2007

hi,  like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right?  so, is there something that i can use to hold those records so that i can do the delete and update just on those records  and don't need to query twice? or is there a way to do that in one go ?thanks in advance! 

View 1 Replies View Related

SqlDataReader Returning Incorrect Results

Oct 23, 2006

I am/have been having an issue with Data Access from a Sql Server database. I have a class that contains a method called "GetDataReader" which takes in a string for the query. Occasionally, the DataReader returned has completely different columns thus resulting in an error when trying to read the data. Below is a small section of code that actually creates the datareader, opens the connection and executes the reader.SqlCommand cmdReader = new SqlCommand();
SqlDataReader drReturn = null;
try {
// Set the connection for the command object
cmdReader.Connection = new SqlConnection(this._csbGlobal.ConnectionString);
cmdReader.Connection.Open();
// Set the command type
cmdReader.CommandType = Type;
// Set the command text
cmdReader.CommandText = Sql;
// Set the command timeout
cmdReader.CommandTimeout = _iTimeout;
if (Parameters != null) {
// Set the parameters
for (int i = 0; i < Parameters.Count; i++) {
cmdReader.Parameters.AddWithValue("@" + Parameters.GetKey(i), Parameters[i]);
}
}

// Get the return value
drReturn = cmdReader.ExecuteReader(CommandBehavior.CloseConnection);
// Dispose of the command object
cmdReader.Dispose();
cmdReader = null;
} catch (SqlException e) {
this.HandleError(e);
} catch (Exception e) {
this.HandleError(e);
}
// Return the reader
return drReturn;The data access class is created on each page and only used for that page and any usercontrols on that page. I have checked all the datareaders and they are all being closed. I have been fighting with this issue for about a month and a half now. It only seems to happen when there are a lot of people on the site.If anyone has experienced this or konws how to fix it please let me know. Thanks-Jason

View 5 Replies View Related

Stored Procedure Not Returning Results

May 15, 2007

Hi,I'm creating a stored procedure that pulls information from 4 tables based on 1 parameter. This should be very straightforward, but for some reason it doesn't work.Given below are the relevant tables:  SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_Project](
[ProjID] [varchar](300) NOT NULL,
[ProjType] [varchar](20) NULL,
[ProjectTitle] [varchar](max) NULL,
[ProjectDetails] [varchar](max) NULL,
[ProjectManagerID] [int] NULL,
[RequestedBy] [varchar](max) NULL,
[DateRequested] [datetime] NULL,
[DueDate] [datetime] NULL,
[ProjectStatusID] [int] NULL,
CONSTRAINT [PK__tbl_Project__0B91BA14] PRIMARY KEY CLUSTERED
(
[ProjID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[tbl_Project] WITH CHECK ADD CONSTRAINT [FK_tbl_Project_tbl_ProjectManager] FOREIGN KEY([ProjectManagerID])
REFERENCES [dbo].[tbl_ProjectManager] ([ProjectManagerID])
GO
ALTER TABLE [dbo].[tbl_Project] CHECK CONSTRAINT [FK_tbl_Project_tbl_ProjectManager]
GO
ALTER TABLE [dbo].[tbl_Project] WITH CHECK ADD CONSTRAINT [FK_tbl_Project_tbl_ProjectStatus] FOREIGN KEY([ProjectStatusID])
REFERENCES [dbo].[tbl_ProjectStatus] ([ProjectStatusID])
GO
ALTER TABLE [dbo].[tbl_Project] CHECK CONSTRAINT [FK_tbl_Project_tbl_ProjectStatus]


-----------------------------------------------------------------


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_Report](
[ReportName] [varchar](50) NOT NULL,
[ProjID] [varchar](300) NULL,
[DeptCode] [varchar](50) NULL,
[ProjType] [varchar](50) NULL,
[ProjectTitle] [varchar](500) NULL,
[ProjectDetails] [varchar](3000) NULL,
[ProjectManagerID] [int] NULL,
[RequestedBy] [varchar](50) NULL,
[DateRequested] [datetime] NULL,
[DueDate] [datetime] NULL,
[ProjectStatusID] [int] NULL,
CONSTRAINT [PK_tbl_Report] PRIMARY KEY CLUSTERED
(
[ReportName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[tbl_Report] WITH CHECK ADD CONSTRAINT [FK_tbl_Report_tbl_ProjectManager] FOREIGN KEY([ProjectManagerID])
REFERENCES [dbo].[tbl_ProjectManager] ([ProjectManagerID])
GO
ALTER TABLE [dbo].[tbl_Report] CHECK CONSTRAINT [FK_tbl_Report_tbl_ProjectManager]
GO
ALTER TABLE [dbo].[tbl_Report] WITH CHECK ADD CONSTRAINT [FK_tbl_Report_tbl_ProjectStatus] FOREIGN KEY([ProjectStatusID])
REFERENCES [dbo].[tbl_ProjectStatus] ([ProjectStatusID])
GO
ALTER TABLE [dbo].[tbl_Report] CHECK CONSTRAINT [FK_tbl_Report_tbl_ProjectStatus]


--------------------------------------------------------------


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_ProjectStatus](
[ProjectStatusID] [int] IDENTITY(1,1) NOT NULL,
[ProjectStatus] [varchar](max) NULL,
CONSTRAINT [PK__tbl_ProjectStatu__023D5A04] PRIMARY KEY CLUSTERED
(
[ProjectStatusID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


-----------------------------------------------------------


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_ProjectManager](
[ProjectManagerID] [int] IDENTITY(1,1) NOT NULL,
[FName] [varchar](50) NULL,
[LName] [varchar](50) NULL,
[Inactive] [int] NULL,
CONSTRAINT [PK__tbl_ProjectManag__7D78A4E7] PRIMARY KEY CLUSTERED
(
[ProjectManagerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

 And here is the stored procedure that I wrote (doesn't return results):  SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetReportQuery]
(
@ReportName varchar(100)
)

AS

BEGIN

SET
NOCOUNT ON

IF @ReportName IS NULL
BEGIN
RETURN -1
END
ELSE
BEGIN

DECLARE @DeptCode varchar(50), @ProjID varchar(50)
SELECT @DeptCode = DeptCode FROM tbl_Report WHERE ReportName = @ReportName

SET @ProjID = @DeptCode + '-' + '%'

SELECT P.ProjID, P.ProjType, P.ProjectTitle, P.ProjectDetails, M.FName, M.LName, P.DateRequested, P.DueDate, S.ProjectStatus
FROM tbl_Project P, tbl_ProjectManager M, tbl_ProjectStatus S
WHERE ((P.ProjID = (SELECT ProjID FROM tbl_Report WHERE ((ReportName = @ReportName))))
AND (P.ProjectDetails = (SELECT ProjectDetails FROM tbl_Report WHERE ReportName = @ReportName) OR P.ProjectDetails IS NULL)
AND (M.FName = (SELECT FName FROM tbl_ProjectManager WHERE (ProjectManagerID = (SELECT ProjectManagerID FROM tbl_Report WHERE ReportName = @ReportName))) OR M.FName IS NULL)
AND (M.LName = (SELECT LName FROM tbl_ProjectManager WHERE (ProjectManagerID = (SELECT ProjectManagerID FROM tbl_Report WHERE ReportName = @ReportName))) OR M.LName IS NULL)
AND (P.DateRequested = (SELECT DateRequested FROM tbl_Report WHERE ReportName = @ReportName) OR P.DateRequested IS NULL)
AND (P.DueDate = (SELECT DueDate FROM tbl_Report WHERE ReportName = @ReportName) OR P.DueDate IS NULL)
AND (S.ProjectStatus = (SELECT ProjectStatusID FROM tbl_Report WHERE ReportName = @ReportName) OR S.ProjectStatus IS NULL)
)
END

END Can someone see what's wrong? Thanks. 

View 7 Replies View Related

OpenXML Not Returning Desired Results

Aug 31, 2007

Hi all,I have a SQL job where I do the following -I check for new rows in my Table "DumpResults", every now and then and get the new rows to be inserted into table "CleanTable". I use OPENXML() to get the new data to be inserted but for some reason I don't get the right data through OPENXML() - DECLARE @intDoc INTDECLARE @xmlDoc VARCHAR(8000)IF(SELECT COUNT(*) FROM DumpResults WHERE DumpResults.C1 NOT IN (SELECT CleanTable.C1 FROM CleanTable)) > 0BEGINSET @xmlDoc = (SELECT * FROM DumpResults WHERE DumpResults.C1 NOT IN (SELECT CleanTable.C1 FROM CleanTable) FOR XML RAW) SET @xmlDoc = '<TABLE>' + @xmlDoc + '</TABLE>'
PRINT @xmlDocEXEC sp_xml_preparedocument @intDoc OUTPUT, @xmlDoc--INSERT INTO CleanTable(C1, C2, C3, C4, C5)
SELECT C1, C2, C3, C4, C5, C6 FROM OPENXML(@intDoc,'/row',1)WITH (C1 INT, C2 CHAR(3), C3 CHAR(3) , C4 FLOAT, C5 INT)EXEC sp_xml_removedocument @intDoc
END
ELSE Output that I get is - <TABLE><row C1="1" C2="AAA" C3="BBB" C4="1.000000000000000e+000" C5="2"/></TABLE>(0 row(s) affected) SO "PRINT @xmlDoc" is returning back the xml data (new results) it collected from the "DumpResults" table which isn't there in "CleanTable" but the "Select... FROM OPENXML(...)" doesn't return any result. why so? If anyone knows please reply If anyone has any better method to do it, inputs are welcome. Thanks  

View 3 Replies View Related

Searching SQL Db And Returning Results To Gridview

Jan 29, 2008

Hello....
I am in the process of building a search function for an application (VS2005, ASP.net, VB code, and AJAX functionality).The user's form has a textbox (for an input string) and two drop-downs.  The user would then click on a "Search Now" button, and the data should populatein a Gridview to the left of the search form.  I'm trying to search over an SQL database and need to know how to exactly implement what I have so far:
<div id="mcb" style="background-color:#2e4b5b; width:195px; height:410px; float:left">     <div id="ht" style="background-color:#1b2c36;padding:10px; border-bottom:solid 1px #fffdff; width:175px;float:left;">           Quick Search      </div><div style="clear:both;"></div>
<div style="padding:10px; background-color:#2e4b5b">      <div id="tfta" style="padding:5px 0px 0px 0px">                <b>Vendor Name</b>                <asp:TextBox ID="txtVendorFilter" runat="server"></asp:TextBox>                <div style="font-size:1px; width:150px; height:1px; background-color:#8FA71F"></div><br />                 <b>Contract Type:</b>                 <asp:dropdownlist ID="ddlContractTypeSearch" runat="server" Width="155px">                           <asp:ListItem Value="0">Select...</asp:ListItem>                           <asp:ListItem Value="1">Vendor Maintenance</asp:ListItem>                           <asp:ListItem Value="2">Consulting Contract</asp:ListItem>                           <asp:ListItem Value="3">Hardware License</asp:ListItem>                           <asp:ListItem Value="4">Software License</asp:ListItem>                           <asp:ListItem Value="5">Statement of Work</asp:ListItem>                           <asp:ListItem Value="6">Admin Svcs. Agreement</asp:ListItem>                           <asp:ListItem Value="7">Master Service Agreement</asp:ListItem>                  </asp:dropdownlist>
           <div style="font-size:1px; width:150px; height:1px; background-color:#8FA71F"></div><br />                   <b>Sort By:</b>                   <asp:DropDownList ID="ddlSortBy" runat="server" Width="155px">                          <asp:ListItem Value="0">Select...</asp:ListItem>                          <asp:ListItem Value="1">Contract Name</asp:ListItem>                          <asp:ListItem Value="2">Contract Type</asp:ListItem>                    </asp:DropDownList>             <div style="font-size:1px; width:150px; height:1px; background-color:#8FA71F"></div><br />        </div>    <br />    <asp:Button ID="btnUpdateFilter" runat="server" Text="Search" width="120px"/>    <asp:Button ID="btnReset" runat="server" Text="Reset" /></div>
</div>
 Here's my select statement used to initially populate the Gridview (set up using the configuration of the Gridview):SELECT [ContractID], [ContractName], [ContractType], [EffectiveDate], [TerminationDate] FROM [Contract]Here's my btnUpdateFilter codebehind (VB):
Protected Sub btnUpdateFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateFilter.Click     Dim strVendorName As String     Dim strContractType As String     Dim strSortBy As String     If txtVendorFilter IsNot "" Then           strVendorName = txtVendorFilter.Text     End If
''''''''''''''''''''''''''''If ddlContractTypeSearch.SelectedValue = 1 Then      strContractType = "1"ElseIf ddlContractTypeSearch.SelectedValue = 2 Then      strContractType = "2"ElseIf ddlContractTypeSearch.SelectedValue = 3 Then      strContractType = "3"ElseIf ddlContractTypeSearch.SelectedValue = 4 Then      strContractType = "4"ElseIf ddlContractTypeSearch.SelectedValue = 5 Then      strContractType = "5"ElseIf ddlContractTypeSearch.SelectedValue = 6 Then      strContractType = "6"ElseIf ddlContractTypeSearch.SelectedValue = 7 Then      strContractType = "7"Else      strContractType = "0"End If
''''''''''''''''''''''''''''''If ddlSortBy.SelectedValue = 1 Then     strSortBy = "ContractName"ElseIf ddlSortBy.SelectedValue = 2 Then     strSortBy = "ContractType"Else     strSortBy = "ContractName"End If
End Sub
 
My question is, "how can I form the proper SQL statement", and then implement it so that my gridview will populate using my generated SQL Statement?
Thank you for the help!!!
-S

View 1 Replies View Related

Returning The Results Of A Linq Query

Feb 29, 2008

I need some help. I have a function that used to use ADO.NET to return a dataview. Now I'm using linq, and I don't know how to make this work anymore.my original function looked like this:    public DataView getIssue()    {       //do some ADO, return the dataview       return ds.Tables["Articles"].DefaultView;    }  With this I could write Gridview1.dataSource = getIssue();I want to do the same thing with Linq, but I'm running into some trouble:Here's my function now:public DataView getIssue()    {        var query = from a in db.Articles        join i in db.Issues on a.IssueID equals i.IssueID       select a;            DataView dv = new DataView();            dv = query.asdatatable();        return query;    }OK, first off I can't use asdatatable since I am using a join, so I can't make the results of my query a dataview. I can't return the results of my query in this function, something that seemed simple to do in Linq now seems like something that may only be possible in ADO.Thanks for your time 

View 5 Replies View Related

Executing A Script And Returning The Results..

Mar 1, 2004

You know how osql can return the results of executing a .sql script to a window? Is there any way to achieve that same behavior in .NET? I am in the process of working on an application that needs to execute a .SQL script (which is easy to do) and then return the actual SQL output from the execution to a window. How do I get that output? None of the sql data objects seem to support this.

View 1 Replies View Related

NOT IN Vs. NOT EXISTS Returning Diff Results

Mar 12, 2004

select count(orgcode)
from orglevel
where orglvl = 1 and exists (select 'x' from empcomp where eecemplstatus = 'A' and eecorglvl1 = orgcode)

26 rows

select count(orgcode)
from orglevel
where orglvl = 1 and orgcode in (select distinct eecorglvl1 from empcomp where eecemplstatus = 'A')

26 rows

select count(orgcode)
from orglevel
where orglvl = 1 and not exists (select 'x' from empcomp where eecemplstatus = 'A' and eecorglvl1 = orgcode)

6 rows

select count(orgcode)
from orglevel
where orglvl = 1 and orgcode not in (select distinct eecorglvl1 from empcomp where eecemplstatus = 'A')

zero rows


Confusing the hell out of me .....

View 2 Replies View Related

Not Returning Results In Production Environment

Oct 7, 2015

I have this script that captures metrics and sizes using T-SQL. When running in development I have no issues. I can run under the context of any database and get results back. When deploying to production servers no results are returning. I'm trying to figure out what permissions are needed for this to return results.

No error message is being returned either. My access is limited for triage against Production? I need to be able to have Production DBA set the right permissions so this job can run correctly.

DECLARE @allocation_table table
(
dbname sysname,
reservedpages bigint,
usedpages bigint,
pages bigint

[Code] ....

View 1 Replies View Related

Max Datetime Returning Multiple Results

Oct 23, 2013

I have a query running without issue on around 100,000 results however i have a couple where my MAX aggregate is returning two results for a MAX(date time) and i cannot figure out why. I have paired down the query to try and work it out but still don't know.

My query now looks like this (i have remove most columns)

SELECT STATUS, RunOn, sort, T_ID
FROM dbo.Results
WHERE (RunOn IN
(SELECT MAX(RunOn)
FROM dbo.Results
group BY T_ID) AND T_ID = 21405)

ORDER BY sort

I added the T_ID = 21405 to restrict the results to the problematic results, if i set T_ID to any other test result i get one value based on the latest RunOn, but for some reason with this T_ID i get two values, the latest one and one slightly older... The date time looks ok, i just can't work out why the latest and one older result are returned !

The original query was grouping by more items but i removed those to try and work out what is going one, as mentioned for 99.9% of results it works perfectly, but for this one i don't know.

View 10 Replies View Related

Query Keeps Returning Slightly Different Results?

Feb 9, 2015

I have a query with a nested query that is used as an in line view. When I run the whole query I keep getting slightly different results each time (10000, 10002, 10001, 9999 etc.), nothing is being changed, no jobs are running on the DB to affect the tables etc.

When I run the inline view query with the nested query, or nested query on its own, it returns same number each time.

What could potentially be the cause of this?

Using SQL Server 2008 R2 Express Edition on local W7 PC

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved