Hello, I have a table called Member in my database that I use to store information about users including the date of birth for each person. I have a search function in my application that is supposed to look through the Member table and spit out a list of users with a user-inputted age range (min and max ages). Now, I could have stored ages instead of dob in the table, but I would think that's bad practice since age changes and would need continuous recomputing (which is db intensive) as opposed to dob which stays the same. So what I'm thinking is getting the min and max user inputted ages, convert them to dob values (of type DateTime) in the application. And then, to query the db and return a list of all users in the Member whose dob falls in between those two dates (is a BETWEEN even possible with DateTime values?). How is the best way to go about this? There are many sites out there that return users with user specified age ranges. Is there a best way to do this that's the least taxing on the db? TIA.
I need to provide a minimum value over a 12 hour time range of data. I'm struggling with performance issues due to the amount of data. Currently I log about 100 devices reporting once per minute into a table. Also about once per minute I need to pull the minimum value reported for each device in the last 12 hours. Currently I'm maintaining a separate table with entries for just the last 12 hours and just performing a Select Min(Temp) Where DeviceID=x, but it already holds about 700,000 records at any given time. The number of devices will increase substantially and this will no longer be viable.
Sample Table ID DeviceID Temp InsertDate 1 10 55 04-28-2015 8:00 AM 2 65 74 04-28-2015 8:00 AM 3 44 23 04-28-2015 8:00 AM 4 10 87 04-28-2015 8:01 AM 5 65 65 04-28-2015 8:01 AM
hi all, I have a table productprice which has the following feildsid price datecreated productname 1 12.00 13/05/2007 a1 2 23.00 14/05/2007 a13 24.00 15/05/2007 a14 56.00 13/05/2007 b15 34.00 18/05/2007 b16 23.00 21/05/2007 b17 11.00 12/02/2007 c1 8 78.00 12/03/2007 c2I need to select the rows that are highlighted here.. ie the row that has the max(datecreated) for all the productname in the table.. plz help thanks in advance..
Hi,In the datawarehouse DB (under MS commerce server 2002) a table storesthe referer domain name. Table structure is likerefererdomainid <binary>,domainInternalFlag<0/1>,refererDomainName<varchar>e.g.<binary>|0|unknown<binary>|1|google.com<binary>|1|yahoo.com<binary>|1|google.com<binary>|1|google.com<binary>|1|google.com<binary>|1|altavista.commy problem is to build a query (using this table only) whichrefererDomainName has the max occurrence and how many times. As in thetable above it is google.com and 4 times.Can anyone help me.Thanks in advance.
Hi there, very sorry if this is the wrong forum to post this in.
I want to know what is the BEST practice, the correct Microsoft way of doing this:
basically, lets say I am inserting a new record into SQL. simple customer record:
firstname
lastname
address
city
postcode
password
dateOfRegistration (SQL has this value and the default value is the getdate())
That's all very well. I want to know how I can get the recordID for this and return that back from the caller (returning is easily done) -
You cannot really after this insertion, perform a SELECT statement to get the LAST record entered, as there maybe several records that could all be inserted at the same time by coincidence. It's not the best way of going about this.
I want to know what is the best way of getting the just inserted record's recordID - I was thinking about using date and time, manually inputting them and then using that to retrieve the last record/current inserting record but again its not the best way of going about doing this.
The following select retrieves multiple reoords for each i.number. How can I select just the first record for each i.number?
SELECT i.number, i.desc, i.it_sdate, v.entry_date FROM itemsnum as I INNER JOIN Inventor as V ON SUBSTR(i.number,1,5)=v.catalog WHERE v.entry_date<ctod("04/01/06") AND i.it_sdate < ctod("04/01/06") order by number, it_sdate desc
hello friends i have table1 and 200 coulumn of table1 :) i have 647.600 records. i entered my records to table1 with for step to code lines in one day :) i select category1 category2 and category3 with select code but i have just one index.. it is productnumber and it is primarykey..So my select code lines is so slow.. it is 7-9 second.. how can i select in 0.1 second ? Should i create index for category1 and category2 and category3 ? But i dont know create index.. My select code lines is below.. Could you learn me and show me index for it ?? or Could you learn me and show me fast Select code lines and index or etc ??? Also my search code line have a dangerous releated to attaching table1 with hackers :) cheersi send 3 value of treview1 node and childnode and child.childnode to below page.aspx :) Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Me.IsPostBack Then If Request("TextBox1") IsNot Nothing ThenTextBox1.Text = Request("TextBox1") End If If Request("TextBox2") IsNot Nothing ThenTextBox2.Text = Request("TextBox2") End If If Request("TextBox3") IsNot Nothing ThenTextBox3.Text = Request("TextBox3") End If End If Dim searchword As String If Request("TextBox3") = "" And Request("TextBox2") = "" Then searchword = "Select * from urunlistesi where kategori= '" & Request("TextBox1") & "'" End If If Request("TextBox3") = "" Then searchword = "Select * from urunlistesi where kategori= '" & Request("TextBox1") & "' and kategori1= '" & Request("TextBox2") & "'" End If If Request("TextBox3") <> "" And Request("TextBox2") <> "" And Request("TextBox1") <> "" Then searchword = "Select * from urunlistesi where kategori= '" & Request("TextBox1") & "' and kategori1= '" & Request("TextBox2") & "' and kategori2= '" & Request("TextBox3") & "'" End If SqlDataSource1.SelectCommand = searchword End Sub
Hi, I want to count the total number of rows in the table "members" and display this result in a ListBox. When I try to run this procedure I get an error message reading "Index out of range exception". What could this mean? BTW, I know that the logic doesn´t make sense. I want to show the number of rows but I try to show a field name. Does anyone have solution, please? I would appreciate the help.
string connectionString2 = ConfigurationManager.ConnectionStrings["ServetteConnectionString"].ConnectionString; //CREATE CONNECTIONSTRING string sQuery2 = "select count(*) from members"; //GET NUMBER OF ROWS OleDbConnection oOleDbConnection2 = new OleDbConnection(connectionString2); oOleDbConnection2.Open(); //CREATE CONNECTION OleDbCommand command2 = new OleDbCommand(sQuery2, oOleDbConnection2); CREATE COMMAND OleDbDataReader reader2 = command2.ExecuteReader(); CREATE READER while (reader2.Read()) { ListBox1.Items.Add new ListItem(reader2["firstName"].ToString())); //THIS LINE RESULTS IN "INDEX OUT OF RANGE EXCEPTION" (STRANGE CODE LOGIC TOO) }
I get this error when exporting to Excel from the designer or from the Report Manager: "Exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
One solution is: (1) One Detail Cell in my table contained a number like #.#########. Aparently this freaks out Excel. I converted it to a string like this: =Convert.ToString(Format((ReportItems!ValueOne.Value / ReportItems!ValueTwo.Value), "#.#########")) This sometimes works but makes the export have text fields and numbers under 0 show just .01 instead of 0.01 for example.
(2) Apparently disabling the Document Map Labels has the same effect and cures the problem - HOW DO YOU DO THIS?????? There is a label property for text boxes - but these are not populated.
Reading the internet..says that the SP2 for SQL server should slolve it. It hasnt.
I am currently investigating the best way to handle partition swapping where the partition scheme is built on several file groups. In order to swap partitions, both partitions need to be on the same file group. In addition, the file groups and partitions are automatically updated once a month meaning that there is a scheduled job that adds a new file group, file group files, and updates the related partition objects.If I am forced to create a new non-partition table on the same file group as the partition of the target table, what would be the best way to create the target table without hard coding the full table definition and clustered index? I know that I can query the systables and syscolumns views to reconstruct a basic SQL statement to build the table definition and views Is there a SQL Server function that I can use to just give me the object definitions? Unfortunately, the OBJECT_ DEFINITION function doesn't apply to tables or indexes. URL....
Hi every body, I am making a program which is currently dealing with thousands of records. What I want is to have a button in the front END which make me able to fetch only first 100 record.If the desired record doesn't come with in first 100 record I press this button another time to fetch next 100 records i.e. from 101 to 199. How can it be possible in SQL Server stored procedure.
Eagerly waiting from all of you GENIUS people. Kailash
I'm trying to read from a table and return only the unique records from a table. The table has 3 columns, ID - Autoinc Amount - decimal 6,2 Name - varchar(10)
I am wanting to retreive only records 3 & 6 (values 0.05 0.06) as they are the only ones where amount is unique i.e. only 1 entry in the table.
I put the following sql statement together which achieves this but it it only returns the amount value select Count(amount),amount from bids group by amount having count(amount)<2 order by amount
So I then expanded it to read select Count(amount),amount,name from bids group by amount,name having count(amount)<2 order by amount not sure where i'm going wrong but the results returned were 0.03 0.03 0.05 0.06 0.07 0.07
I receive this error during rendering when I have two cells merged together:
Error Snippet
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
When I "Split Cells" on the offending cells, it starts to work. This report renders without error when run on the RS server. This error only occurs when running the report locally on the "Preview" tab in the report designer.
I have closed the IDE and deleted the *.data files and restarted with the same results. Is there anyway to get more information about the error to help debug the problem?
I have some VB.NET code to retrieve data from an SQL Server database and display it. The code is as follows: ------------------------------------------------------------------------------------------------------- sw_calendar = calendarAdapter.GetEventByID(cid) If sw_calendar.Rows.Count > 0 Then
lblStartDateText.Text = "*** Not Found ***" lblEndDateText.Text = "*** Not Found ***" lblTitleText.Text = "*** Not Found ***" lblLocationText.Text = "*** Not Found ***" lblDescriptionText.Text = "*** Not Found ***" End If ------------------------------------------------------------------------------------------------------- If all of the fields in the database has values, everything works ok. However, if the title, location or description fields have a null value, I receive the following error message: Unable to cast object of type 'System.DBNull' to type 'System.String'. I've tried a bunch of different things such as:
Adding ".ToString" to the database field, Seeing if the value is null: If sw_calendar(0).description = system.DBnull.value... ...but either I get syntax errors in the code, or if the syntax is ok, I still get the above error message. Can anyone help me with the code required to trap the null within the code example I've provided? I'm sure there are other, and better, ways to code this, but for now I'd really like to get it working as is, and then optimize the code once the application is working (...can you tell I have a tight deadline )
I am having trouble returning the correct record with my stored procedure. my problem is that i don't know how to structure the sql statement to do the following: given a set of records that have the same loankey, i need to 1. find the record that has most recent date (lockExprDt) 2. for all records with that date, find the highest Lock Number (LockNo) 3. for the all the records with that date and that LockNo, find the highest extension number (Ext) currently my sql statement returns a record that has the most recent date. i don't now how to write the sql to further define my query to return the record that has the most recent date with highest lock number, and finally the highest extension number. any suggestions as to what i am doing wrong. below is my slq statement. please note that i need to add the sql that will query for the max LockNo, and max Ext. Any help is greatly appreciated. thx! select a.loankey, a.lockrate, a.investor, a.price, a.ext, a.cost, a.lockno, a.lockstatus , CASE WHEN CONVERT(CHAR(8),a.lockdate,10)='12:00:00 AM' THEN NULL ELSE CONVERT(CHAR(8),a.lockdate,10) END as 'LockDate' , CASE WHEN CONVERT(CHAR(8),b.lockExprDt,10)='12:00:00 AM' THEN NULL ELSE CONVERT(CHAR(8),b.lockExprDt,10) END as 'LockExprDt' , Case WHEN CONVERT(CHAR(8),b.lockExprDt,10)>= CONVERT(CHAR(8),GETDATE(),10) THEN datediff(day, CONVERT(CHAR(8),GETDATE(),10), CONVERT(CHAR(8),b.lockExprDt,10)) ELSE NULL END as 'Days' from cfcdb..locktable ainner join (select loankey, max(lockExprDt) as lockExprDtfrom cfcdb..locktablegroup by loankey) bON a.loankey = b.loankey AND a.lockExprDt = b.lockExprDt where a.loankey = @LoanKey
I HAVE THIS SQL STATEMENT WHICH GET THE MIN(AMOUNT) and MAX(AMOUNT) and DISPLAY IT IN A SINGLE ROW. HOW CAN I GET THE RECORD BEFORE THE MAX (AMOUNT) INBETWEEN DATES IN CASE THERE ARE 4 RECORDS WITH SAME EMPLOYEENO IN THE DATE RANGE SPECIFICIED ? THIS IS SORTED BY EMPLOYEENO AND STARTDATE DESC
SELECT EmployeeNo, StartDate AS StartDate, MIN(Amount) AS oldsalary, EndDate AS EndDate, BenefitCode, (SELECT TOP 1 MAX([amount]) FROM EMPBENEFITS T2 WHERE T2.employeeno = T.employeeno AND startdate >= '2001-06-01' AND startdate <= '2007-06-02') AS newsalary FROM dbo.empBenefits T WHERE (StartDate IN (SELECT TOP 1 ([startdate]) FROM EMPBENEFITS T1 WHERE T1.employeeno = T.employeeno AND Benefitcode <> 'HON' AND startdate >= '2001-06-01' AND startdate <= '2007-06-02')) GROUP BY EmployeeNo, Amount, BenefitCode, StartDate, EndDate, Amount ORDER BY EmployeeNo, StartDate DESC
I am currently using this SQL code to capture some records over the last 2 months and it has been working great. I am now being asked if I can change this code with specifications:
1) Scan the records in the system until the count (*) as Volume reaches 30 because they prefer that as a denominator when figuring an average
2) Only run the scan for a maximum of 6 months.
So, there will most likely be some records that do not reach a volume number of 30 in this date range. In this instance we will just take the maximum volume number reached at 6 months.
So, how can I write this so it will build the file each time a record has reached the maximum of 30 and keep scanning back until we reach 6 months? If someone could lead me in the right direction on the proper order of the methodology in my code to accomplish these results it would be greatly appreciated. Desperate!
declare @startdate smalldatetime, @enddate smalldatetime , @month int, @year int
pe1.patev_loc_id as LocID, pp_cproc_id_r as ProcID, count (*) as Volume, sum (datediff (mi, pe1.patev_event_time, pe2.patev_event_time)) as Minutes, sum (datediff (mi, pe1.patev_event_time, pe2.patev_event_time))/count(*) as AvgMin
from risdb_rch08_stag..performed_procedure (index pp_serv_time_r_ndx), risdb_rch04_stag..patient_event pe1, risdb_rch04_stag..patient_event pe2
where pp_service_time_r between @Startdate and @Enddate and pp_asn_req_no = pe1.patev_asn_req_no and pp_asn_seq_no = pe1.patev_asn_seq_no and pp_status_v = 'CP' and pp_rep_id > 0 and pe1.patev_event_code = 'PB' and (pp_asn_req_no = pe2.patev_asn_req_no and pp_asn_seq_no = pe2.patev_asn_seq_no and pe2.patev_event_code = 'PL') and datediff (mi, pe1.patev_event_time, pe2.patev_event_time) > 0
Hi, first off, I'm a TOTAL novice at this stuff, I'm just currently blundering my way through a complex site to learn stuff. I'm trying to call the newest addition to a SQL database into a webpage, in this case, it'll be 'newest user', one result only. I've done several other data retrival sections using a datatable, but the guy who was helping me though it is unavailable at the moment and I get the feeling I've jumped into the deepend slightly. Could anyone give me an example of how retrieving the First N Records from SQL should look in VS? Does it need to be in a data table or can it go in a label? Sorry if this is somewhat vague, but as I said, I've really only been using VS for a week!
I want to create sql for retrieving 10 records per time but need to know the total result matches. And I have previous and next button for retrieving previous or next 10 records.
I need help with this. When I run the below script (only select) it retrives around 130K records and gives me the output within 2 mins. Whenever I try to put the same output in a temp or permanent table it takes hours. Any Idea why?
SET NOCOUNT ON
DECLARE @ImportId INT SET @ImportId = 5151
DECLARE @ResultXML XML SET @ResultXML = (SELECT ResultXML FROM tbRequests WITH(NOLOCK) WHERE ImportId = @ImportId)
SELECT resultNode.value('(./DealName)[1]','VARCHAR(200)') AS DealName, resultNode.value('(./CUSIP)[1]','VARCHAR(100)') AS CUSIP, CASE WHEN resultNode.value('(./Vintage)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./Vintage)[1]','INT') END AS Vintage, resultNode.value('(./PoolPoolType)[1]','VARCHAR(100)') AS PoolType, CASE WHEN resultNode.value('(./PaidOff)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./PaidOff)[1]','BIT') END AS PaidOff FROM @ResultXml.nodes('./WebService1010DataOutput') resultXml(resultXmlNode) CROSS APPLY resultXmlNode.nodes('./Results/Result') resultNodes(resultNode)
INSERT into #TResults (DealName,CUSIP,Vintage,PoolType,PaidOff) SELECT resultNode.value('(./DealName)[1]','VARCHAR(200)') AS DealName, resultNode.value('(./CUSIP)[1]','VARCHAR(100)') AS CUSIP, CASE WHEN resultNode.value('(./Vintage)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./Vintage)[1]','INT') END AS Vintage, resultNode.value('(./PoolPoolType)[1]','VARCHAR(100)') AS PoolType, CASE WHEN resultNode.value('(./PaidOff)[1]','VARCHAR(100)') = '' THEN NULL ELSE resultNode.value('(./PaidOff)[1]','BIT') END AS PaidOff FROM @ResultXml.nodes('./WebService1010DataOutput') resultXml(resultXmlNode) CROSS APPLY resultXmlNode.nodes('./Results/Result') resultNodes(resultNode)
CREATE TABLE [dbo].[tblSubscription]( [SubscriptionID] [int] IDENTITY(1000000,1) NOT NULL, [SubscriberID] [int] NOT NULL, [Status] [int] NOT NULL, [JournalID] [int] NOT NULL,
CREATE TABLE [dbo].[tblTransaction]( [TransactionID] [bigint] IDENTITY(100000000,1) NOT NULL, [TransactionTypeID] [int] NOT NULL, [SubscriptionID] [int] NOT NULL, [Created] [datetime] NOT NULL,
CREATE TABLE [dbo].[tblMailing]( [MialingID] [bigint] IDENTITY(1000000000,1) NOT NULL, [SubscriptionID] [int] NOT NULL, [MailTypeID] [int] NOT NULL, [MailDate] [datetime] NOT NULL
So for each subscription there can be 1 or more transactions and 0 or more mailings, and the mailings are not necassarily related to the transactions. What I am having difficulty doing is this:
I wish to select tblMailing.MailingID, tblMailing.MailDate, tblMailing.SubscriptionID (or tblSubscription.SubscriptionID), tblSubscription.SubscriberID, tblSubscription.Status, tblTransaction.TransactionID, tblTransaction.Created, but I only wish to retrieve rows from the transaction table where tblTransaction.Created is the latest dated transaction for that subscription. I.E. (maybe this makes more sense..:) I wish to select all rows from tblMailing along with each mailing's relevent subscription details, including details of the LATEST TRANSACTION for each of those subscriptions.
I am currently working along the lines of MAX(tblTransaction.Created) and possibly GROUP BY in a subquery, but cannot quite figure out the logic.
I'm Using a CLR for creating a trigger on database tables, This is my Exception : A .NET Framework error occurred during execution of user defined routine or aggregate 'AvailableFlightTrgg': System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.ArgumentOutOfRangeException: at System.Collections.ArrayList.get_Item(Int32 index) at Triggers.AvailableFlightTrgg() . A .NET Framework error occurred during execution of user defined routine or aggregate 'AvailableFlightInsert': System.Data.SqlClient.SqlException: A .NET Framework error occurred during execution of user defined routine or aggregate 'AvailableFlightTrgg': System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.ArgumentOutOfRangeException: at System.Collections.ArrayList.get_Item(Int32 index) at Triggers.AvailableFlightTrgg() . INSERT [SamaCRSHistory].[dbo].[AvailableFlight] VALUES ('283','50','23','4','2','6','15','1','5','4','5/25/2008 8:30:00 AM','5/25/2008 7:00:00 AM','6/26/2008 12:00:00 AM','5','AR2580','125','0','False','False','1','Flight created on 5/25/2008 00:00:00','1', 'I', GETDATE()); INSEA .NET Framework error occurred during execution of user defined routine or aggregate 'AvailableFlightTrgg': System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.ArgumentOutOfRangeException: at System.Collections.ArrayList.get_Item(Int32 index) at Triggers.AvailableFlightTrgg() . A .NET Framework error occurred during execution of user defined routine or aggregate 'AvailableFlightInsert': System.Data.SqlClient.SqlException: A .NET Framework error occurred during execution of user defined routine or aggregate 'AvailableFlightTrgg': System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.ArgumentOutOfRangeException: at System.Collections.ArrayList.get_Item(Int32 index) at Triggers.AvailableFlightTrgg() . INSERT [SamaCRSHistory].[dbo].[AvailableFlight] VALUES ('283','50','23','4','2','6','15','1','5','4','5/25/2008 8:30:00 AM','5/25/2008 7:00:00 AM','6/26/2008 12:00:00 AM','5','AR2580','125','0','False','False','1','Flight created on 5/25/2008 00:00:00','1', 'I', GETDATE()); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','7','125','125','0','0','Flight created on 5/25/2008 00:00:00','1'); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','4','25','25','20','20','Flight created on 5/25/2008 00:00:00','1'); The statement has been terminated. System.Data.SqlClient.SqlException: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.DispatchMessages(Boolean ignoreNonFatalMessages) at Microsoft.SqlServer.Server.SmiEventSink_Default.DispatchMessages(Boolean ignoreNonFatalMessages) at System.Data.SqlClient.SqlCommand.RunExecuteNonQuerySmi(Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteToPipe(SmiContext pipeContext) at Microsoft.SqlServer.Server.SqlPipe.ExecuteAndSend(SqlCommand command) at StoredProcedures.AvailableFlightInsert(Decimal AvailableFlightTimeTableID, Decimal Availabl... INSERT [SamaCRSHistory].[dbo].[AvailableFlight] VALUES ('283','50','23','4','2','6','15','1','5','4','5/25/2008 8:30:00 AM','5/25/2008 7:00:00 AM','6/26/2008 12:00:00 AM','5','AR2580','125','0','False','False','1','Flight created on 5/25/2008 00:00:00','1', 'I', GETDATE()); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','7','125','125','0','0','Flight created on 5/25/2008 00:00:00','1'); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','4','25','25','20','20','Flight created on 5/25/2008 00:00:00','1');RT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','7','125','125','0','0','Flight created on 5/25/2008 00:00:00','1'); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','4','25','25','20','20','Flight created on 5/25/2008 00:00:00','1'); The statement has been terminated. System.Data.SqlClient.SqlException: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.DispatchMessages(Boolean ignoreNonFatalMessages) at Microsoft.SqlServer.Server.SmiEventSink_Default.DispatchMessages(Boolean ignoreNonFatalMessages) at System.Data.SqlClient.SqlCommand.RunExecuteNonQuerySmi(Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteToPipe(SmiContext pipeContext) at Microsoft.SqlServer.Server.SqlPipe.ExecuteAndSend(SqlCommand command) at StoredProcedures.AvailableFlightInsert(Decimal AvailableFlightTimeTableID, Decimal Availabl... INSERT [SamaCRSHistory].[dbo].[AvailableFlight] VALUES ('283','50','23','4','2','6','15','1','5','4','5/25/2008 8:30:00 AM','5/25/2008 7:00:00 AM','6/26/2008 12:00:00 AM','5','AR2580','125','0','False','False','1','Flight created on 5/25/2008 00:00:00','1', 'I', GETDATE()); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','7','125','125','0','0','Flight created on 5/25/2008 00:00:00','1'); INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('283','4','25','25','20','20','Flight created on 5/25/2008 00:00:00','1'); This is my Code :case TriggerAction.Insert:using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open();command = new SqlCommand(@"SELECT * FROM INSERTED;", connection); dr = command.ExecuteReader(); dr.Read();AvailableFlightID = (Decimal)dr[0]; AvailableFlightTimeTableID = (Decimal)dr[1];AvailableFlightAirlineID = (Decimal)dr[2]; AvailableFlightRoutingID = (Decimal)dr[3];AvailableFlightAPTerminalIDOrg = (Decimal)dr[4]; AvailableFlightAPTerminalIDDest = (Decimal)dr[5];AvailableFlightAirCraftID = (Decimal)dr[6]; AvailableFlightFlightStatusID = (Decimal)dr[7];AvailableFlightCateringID = (Decimal)dr[8]; AvailableFlightPayLoadTableID = (Decimal)dr[9];AvailableFlightArrTime = (DateTime)dr[10]; AvailableFlightDeptTime = (DateTime)dr[11];AvailableFlightDate = (DateTime)dr[12]; AvailableFlightDayName = (int)dr[13];AvailableFlightFlightNo = (String)dr[14]; AvailableFlightCapacity = (int)dr[15];AvailableFlightFreeBaggage = (int)dr[16]; AvailableFlightHaveChild = (bool)dr[17];AvailableFlightHaveParrent = (bool)dr[18]; AvailableFlightCommissionPercent = (int)dr[19];AvailableFlightRemark = (String)dr[20];AvailableFlightUserID = (Decimal)dr[21]; dr.Close();f (AvailableFlightID != 0) {command = new SqlCommand(@"INSERT [SamaCRSHistory].[dbo].[AvailableFlight] VALUES ('" + AvailableFlightID + @"','" + AvailableFlightTimeTableID + @"','" + AvailableFlightAirlineID + @"','" + AvailableFlightRoutingID + @"','" + AvailableFlightAPTerminalIDOrg + @"','" + AvailableFlightAPTerminalIDDest + @"','" + AvailableFlightAirCraftID + @"','" + AvailableFlightFlightStatusID + @"','" + AvailableFlightCateringID + @"','" + AvailableFlightPayLoadTableID + @"','" + AvailableFlightArrTime + @"','" + AvailableFlightDeptTime + @"','" + AvailableFlightDate + @"','" + AvailableFlightDayName + @"','" + AvailableFlightFlightNo + @"','" + AvailableFlightCapacity + @"','" + AvailableFlightFreeBaggage + @"','" + AvailableFlightHaveChild + @"','" + AvailableFlightHaveParrent + @"','" + AvailableFlightCommissionPercent + @"','" + AvailableFlightRemark + @"','" + AvailableFlightUserID + @"', '" + "I" + @"', " + "GETDATE()" + @");", connection); pipe.Send(command.CommandText); command.ExecuteNonQuery();command = new SqlCommand(@"SELECT TimeTableSubClassSubClassID , TimeTableSubClassMaxCapacity, TimeTableSubClassWaitListCapacity FROM [SamaCRS].[dbo].[TimeTableSubClass] Where TimeTableSubClassTimeTableID = '" + AvailableFlightTimeTableID + "'", connection); dr = command.ExecuteReader(); System.Collections.ArrayList SubClassIDList = new System.Collections.ArrayList(); System.Collections.ArrayList SubClassCapacityList = new System.Collections.ArrayList();System.Collections.ArrayList SubClassWaitListCapacityList = new System.Collections.ArrayList();while (dr.Read()) { SubClassIDList.Add(dr["TimeTableSubClassSubClassID"]);SubClassCapacityList.Add(dr["TimeTableSubClassMaxCapacity"]);SubClassWaitListCapacityList.Add(dr["TimeTableSubClassWaitListCapacity"]); } dr.Close(); SubClassIDList.TrimToSize(); SubClassCapacityList.TrimToSize(); SubClassWaitListCapacityList.TrimToSize();int CountID = SubClassIDList.Count;for (int i = 0; i <= CountID; i++) { command = new SqlCommand(@"INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('" + AvailableFlightID + @"','" +SubClassIDList[i] + @"','" + SubClassCapacityList[i] + @"','" + SubClassCapacityList[i] + @"','" + SubClassWaitListCapacityList[i] + @"','" + SubClassWaitListCapacityList[i] + @"','" + AvailableFlightRemark + @"','" + AvailableFlightUserID + @"');", connection); pipe.Send(command.CommandText); command.ExecuteNonQuery(); }
////---------------------------------------- }
} break;
this Code doesnt Work , but before writing this one I used the Code Below and It was working perfectly, Previous Working Code : //Initialize all TimeTable Classes for Created Flightcommand = new SqlCommand(@"SELECT TimeTableSubClassSubClassID FROM [SamaCRS].[dbo].[TimeTableSubClass] Where TimeTableSubClassTimeTableID = '" + AvailableFlightTimeTableID + "'", connection); dr = command.ExecuteReader(); System.Collections.ArrayList SubClassIDList = new System.Collections.ArrayList();while (dr.Read()) { SubClassIDList.Add(dr.GetValue(0)); } dr.Close(); SubClassIDList.TrimToSize();foreach (object AvailableFlightSubClassID in SubClassIDList) {command = new SqlCommand(@"INSERT [SamaCRS].[dbo].[AvailableFlightSubClass] VALUES ('" + AvailableFlightID + @"','" + AvailableFlightSubClassID + @"','" + AvailableFlightCapacity + @"','" + AvailableFlightCapacity + @"','" + 0 + @"','" + 0 + @"','" + AvailableFlightRemark + @"','" + AvailableFlightUserID + @"');", connection); pipe.Send(command.CommandText); command.ExecuteNonQuery(); }
Can ANy one Help me with this Exception , I have Checked The Tables for Number of Columns , its not from Column numbers ,I Think iys from For() Loop????????
I have a fairly complex SP with 3 tables the idea being to display a Region, Client and EventI want to show only the last event for each client I have replaced my event table with a View which returns the TOP 1 but all I get is the most recent of all records I want eg:Region 1, Client 1, Most recent event Region 1, Client 2, Most recent event Region 1, Client 3, Most recent event
If I know the exact offset I can query easily enough using PropClass and the exact offset. But what if the offset is not included in the range for a given PropClass? How can I get a query to return the last valid record for a given PropClass from within a join?
For example, if my query contained PropClass = 1 and offset = 4, it should return the Amount of .50 from Record with ID 3
This is a query that I am trying to work on:
Code: SELECT v.District, v.PropClass, YearAquired, SUM(cost * cnt), SUM(v.Cost * v.Cnt * t.Amount), SUM(v.Tax), COUNT(*) FROM UPValue v INNER JOIN UPMaster m on m.Year = v.year and m.Account = v.account INNER JOIN UPTable T on t.PropClass = v.PropClass and t.Offset = v.Year - v.YearAquired WHERE v.Year = 2012 and LeaseType = 2 group by v.District, v.PropClass, YearAquired order by v.District, v.PropClass
Using <= will not work because that would return multiple records from UPTable when the offset is < the max offset.
I have a situation where an agent has number of activities for a certain date range. If an agent has multiple activities within certain date range, I would like BALANCE BEFORE from the first activity and BALANCE AFTER from the last activity. Here is my current SQL query that returns the following data:
DECLARE @BeginDate Datetime DECLARE @EndDate Datetime Set @BeginDate = '05-1-2015' Set @EndDate = '05-31-2015' SELECT a.AgentName, R.BALANCEBEFORE,
[Code] ....
AGENTNAME BALANCE BEFORE BALANCE AFTER DATE DOUGLAS 9738.75 9782.75 2015-05-11 DOUGLAS 9782.75 9804.75 2015-05-12 DOUGLAS 9804.75 9837.75 2015-05-13
In the sample data above, ideally I would like my query to return data as follow:
AGENTNAME BALANCE BEFORE BALANCE AFTER DOUGLAS 9738.75 (from first activity) 9837.75 (from last activity)
Not sure how I can write sql query to accomplish this.
I am unable to migrate any DTS packages, from a SQL Server 2000 package, from a structured storage file, or from a DTS package imported into SQL2005 (Developer Edition, 32 bit). Running the Package Migration Wizard, every time I get to the List Package screen, i get the error below. I haven't found any other mention of this so far. Anyone else seen this error or have suggestions?