Hi all,
I have a table with 2 columns (simplified for this question):
Date and Action
Date is normal datetime, Action is varchar and can be either Sent or Received. The data can look like this:
1. '2008-04-02 15:09:09.847', Sent
2. '2008-04-02 15:09:10.125', Sent
3. '2008-04-02 15:09:11.125', Received
4. '2008-04-02 15:09:12.459', Received
5. '2008-04-02 15:09:15.459', Received
6. '2008-04-02 15:09:24.121', Sent
7. '2008-04-02 15:09:28.127', Received
I want to find a pair of rows Sent-Received with the Max Date difference, where Received follows immediately after Sent.
It means in our example, valid are only lines
2. and 3. or
6. and 7.
In this example, rows 6. and 7. have bigger difference of Dates, so the result of the query should be
6. '2008-04-02 15:09:24.121', Sent, 7. '2008-04-02 15:09:28.127', Received
It is probably easy, I just cannot work it out. Suprisingly finding MIN was quite easy. Thanx for any tips!
Regards,
alvar
I have my db in a pocket pc wm5.0, I just want to make a simple query select * from table where pk = '1' but this doesnt work, if you tried any other field else than the primary key it works... WHY???
would it be a problem with the sdf file? help please!!!
I am kicking myself, but cannot seem to get a simple stored procedure to return ANY records. I know it's soming that has to do with the Joins. Don't know what. I ran query analyzer and passed it a valid city and nothing was returned, but no errors either. If I run the query without any parameters, all the records are retrieved fine. ANY IDEAS?
Can someone please help me fix this. The if statement always runs. I only want it to run if the statement is true and there is a result coming back. If the productID does not have any magazines linking to it, I don't want the If statement to run. Thanks in advance.
ASP.NET code:
If Not Magazine.GetMagazinesForProduct(ProductID) Is Nothing Then blanklabel.Text = categoryDetails.Spacer blanklabel.Visible = True blanklabel2.Text = categoryDetails.Spacer blanklabel2.Visible = True magazinerecommendedlabel.Text = "Recommended/Featured in the following magazine(s):" magazinerecommendedlabel.Visible = True End If -------------------------
magazine class:
Public Function GetMagazinesForProduct(ByVal productID As String) As SqlDataReader Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("GetMagazinesForProduct", connection) command.CommandType = CommandType.StoredProcedure
Return command.ExecuteReader(CommandBehavior.CloseConnection) End Function
-----------------------
Stored Procedure:
CREATE PROCEDURE GetMagazinesForProduct (@ProductID varchar) AS SELECT Magazine.[Name], Magazine.[Issue], Magazine.SmallImagePath FROM Magazine INNER JOIN MagazineProduct ON Magazine.MagazineID = MagazineProduct.MagazineID WHERE MagazineProduct.ProductID = @ProductID RETURN GO
Hi all, I have a problem with this trigger. It seams to be very simple, but it doesn't work...
I created a trigger on a table and I would want that this one updates a field of a table on a diffrent DB (Intranet). When I test it normally (a real situation), it doesn't work, but when I do an explicit update ("UPDATE AccesCard SET LastMove = getDate();" by example) it works.
If anyone could help me, I would appreciate.
NB: Is there a special way, in a trigger, to update a table when the table to update is on another BD ?
Francois
This is the trigger: ------------------------------------------------------------
ALTER TRIGGER UStatus ON AccesCard AFTER UPDATE, INSERT AS
DECLARE @noPerson int
SET NOCOUNT OFF
IF UPDATE(LastMove) BEGIN SELECT @noPerson = Person FROM INSERTED UPDATE Intranet.dbo._Users SET Intranet.dbo._Users.status = 1 WHERE personNo = @noPerson; END
***Disclaimer*** This is homework, just need a hint.
I compare this to other scripts and can't find any differences. I'm getting a syntax error:
Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '('. Msg 102, Level 15, State 1, Line 3 Incorrect syntax near '('. Msg 102, Level 15, State 1, Line 3 Incorrect syntax near '('.
Any hints would be great! Thanks.
USE StateUBookstore
ALTER TABLE dbo.Classes ADD( InstructorID char (5) NOT NULL, Credits int NOT NULL); GO
ALTER TABLE dbo.Students ADD( PhoneNO char(14) NULL, Email char (50) NULL), DROP COLUMN BookStoreEmp; GO
ALTER TABLE dbo.Enrollment ADD( Semester int NOT NULL, EndDate DateTime NOT NULL);
I tried to create a simple application based on the Sql Server CE samples and, as is typical when I play with databases, the program failed. In this case it failed to even load. The program has a form and a data source that I dropped onto the form. When I run the program the program breaks at this line:
Code Snippetthis._connection = new global::System.Data.SqlServerCe.SqlCeConnection();
The error is:
An unhandled exception of type 'System.DllNotFoundException' occurred in System.Data.SqlServerCe.dll Additional information: Unable to load DLL 'sqlceme35.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
My first attempt at 'fixing' this was simply to copy the requisite DLLs to my bindebug folder. I found the DLLs here: C:Program Files (x86)Microsoft SQL Server Compact Editionv3.5 and copied these - sqlcecompact35.dll, sqlceca35.dll, sqlceme35.dll, sqlceoledb35.dll, sqlceqp35.dll and sqlcese35.dll, sqlceer35EN.dll - to my bindebug folder.
Now instead of the first error, I get this error:
An unhandled exception of type 'System.BadImageFormatException' occurred in System.Data.SqlServerCe.dll Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
I am running Vista Business (x64) and using (the desktop version of) Sql Server Compact Edition 3.5 with Visual Studio 2008 Standard Edition. The test 'program' is written in C#. (Incidentally I can play with the database with no problems in Visual Studio 2008's server explorer. I can look at data, add data, etc.)
I'm trying to work my way through the steps of using a User Id and Password in a connection string.
I'm working with SQL 2005 Express, VS2005, in the development server. Got an error I can't get around...tried it several diffent ways on a slightly more complicated test site...no joy...so went to the MSDN tutorial...made the most "vanilla" test I could think of, and still can't figure it out.
I thought it would be simple enough that I could post the whole thing (below)
The test works fine with Integrated Security = True in the connection string. When I remove that phrase, I get the error:
{"CREATE DATABASE permission denied in database 'master'. An attempt to attach an auto-named database for file E:MyPathApp_DataVSST_DB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."}
This occurs on the cn.Open statement below.
It gets past the login, so I know that the SQL User and password match up correctly.
========================= Page Code Behind (no controls on page) ------------
Imports System.Data Imports System.Data.SqlClient
Partial Class _Default Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("VSST_CN").ToString())
Dim cmd As SqlCommand = New SqlCommand("SELECT COUNT(*) FROM VSST_Table", cn) cn.Open() Dim rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) rdr.Read() Response.Write(rdr(0).ToString())
End Sub End Class
================= The DB
Table VSST_Table, ID is int, primary key, identity Field1, Field2, Field3, Field4, Field5 are varchar(50)
I added one record ("A", "B", "C", "D", "E") to the table through VS2005 Server Explorer
This shows up in Count = 1 from running the page when Integrated Security = True
================= In SSMSE: (this is ALL I did, tried to use the minimum so not to confuse...)
I added the SQL Authentication Server level user "VSST" with the password "vsst123" (and the login works, as noted above)
I attach the .mdf
I add VSST to the Database Users, and give it db_owner
I add VSST to the Table with all permissions checked.
=====================================
I can't figure this out. This is a very vanilla test and I'm stumped. I'm about to give up on SQL Authentication entirely (at least for now), and just try to filter my inputs for SQL Injections...that's the only reason I have (at this stage in my biz plan) for needing SQL Authentication. On the other hand, I really don't like being this stumped on something that is so widely promoted as a common practice.
This is simple enough and I'm stumped. Why doesn't this work?
Code Snippet use w go -- Create image warehouse create table dbo.ImageWarehouse ( [ImageWarehouseID] int identity(1,1) primary key, [ImageName] varchar(100), Photo varbinary(max)) Go -- Import image Insert into dbo.ImageWarehouse ([ImageName]) values ('testingimage.gif') update dbo.ImageWarehouse set Photo = (SELECT * FROM OPENROWSET(BULK 'c: estingimage.gif', SINGLE_BLOB)AS x ) WHERE [ImageName]='testingimage.jpg' go -- Check population --delete from dbo.ImageWarehouse select * from dbo.ImageWarehouse go -- Export image declare @SQLcommand nvarchar(4000) set @SQLcommand = 'bcp "SELECT top 1 Photo FROM w.dbo.ImageWarehouse WHERE ImageName = ''testingimage.gif''" queryout "c: estingimage_out.gif" -T -N -S [my server name]' exec xp_cmdshell @SQLcommand go
But testingimage_out.gif is unreadable. It's the same size (28k) as the original trestingimage.gif. Same result with a .jpg file. Try to open the file and it's just red X.
No SQL errors. Just result error. What am I overlooking?
I currently have a simple cdosys email task that has been scheduled to send a simple email from ssis. The email is sent using an activex script in a "SQL 2000 DTS Package Task". When executed manually, the email is sent ok. When scheduled (and run under our SQL agent account), it fails. Can anyone point me in the right direction? Is this a permissions issue?
'-- this script seems to cause problems, but only when scheduled -- dim mailer set mailer = CreateObject("CDO.Message") dim cdoconfig const cdoDispositionNotificationTo = "urn:schemas:mailheader:disposition-notification-to" const cdoReturnReceiptTo = "urn:schemas:mailheader:return-receipt-to" set cdoconfig = CreateObject("CDO.Configuration")
with mailer set .Configuration = cdoconfig .BodyPart.charset = "unicode-1-1-utf-8" .BodyPart.ContentTransferEncoding = "quoted-printable" .Fields("urn:schemas:httpmail:importance").Value = 2 .Fields.Update
.Subject = "Notification" .From = "donotreply@test.com" .TextBody = "TEST" .Bcc = "someone@test.com" .Send end with '-------------
Also, since I have several DTS packages that are similar, I'd like to keep these packages in the SQL 2000 dts format, instead of converting them into SSIS format and using database mail.
I have installed VS 2008 Beta 2 which includes SQL CE 3.5, (I have VS 2005 installed too).
I can not get any INSERT command to work!
First i have tried the VS wizard for a new connection and a dataset. but after inserting a row into one of the dataset tables and then updating it to SQL CE with tha data adapter, nothing happens! NO ERROR and NO inserted row in the database file! so the identity of the inserted row in dataset table doesnt get updated.
Then i tried a simple code without any dataset in a clean solution:
Code Snippet
Dim con As New SqlCeConnection("Data Source=|DataDirectory|MyDatabase#1.sdf") Dim cmd As New SqlCeCommand("INSERT INTO [Table1](Name) VALUES('TestValue')", con) Try con.Open() cmd.ExecuteNonQuery() Catch ex As SqlCeException MessageBox.Show(ex.Message) Finally con.Close() End Try NO ERROR! NO INSERTED ROW! Nothing happen!
hello it seems lack of c# skills is getting the better of me here...iv been trying to get this to work for hours now without success. I have just started working in c# so i am a beginner :) all i want to do it query the database, check to see if a title exists, if yes then populate textbox saying 'title in use' but if the title doesnt exists then continue executing rest of code to add the title. You'll notice iv tried to use string variables and sqlDataAdapter but i cant get these to work either...please help so far i have this that keeps giving me the error that my button click is undefined: protected void bookButton_Click(object sender, EventArgs e){ //string title;try{SqlConnection conn1 = new SqlConnection(); conn1.ConnectionString = "Data Source=Gemma-PC\SQLEXPRESS;" +"Initial Catalog=SoSym;" + "Integrated Security=SSPI;";SqlCommand findTitle = new SqlCommand("SELECT title FROM Publication WHERE title='" + titleTextBox.Text + "';", conn1);
conn1.Open(); findTitle.ExecuteNonQuery(); /* DataSet myDataSetTitle = new DataSet("PublicationTitle"); myDataSetTitle.Clear(); myDataAdapterTitle.Fill(myDataSetTitle);//myDataSet contains results from above SELECT statement title = myDataSetTitle.Tables[0].Rows[0]["title"].ToString();*/ }catch(Exception ex) {TitleInvalidMessage.Text = "Title Not Accepted: This title is already in use by another publication" +ex.Message; } //title does not exist in table so continue and add to database //rest of code here
I am trying to make a single display page for an author's books.the books page only displays books of a type "type" (novels, non-fiction, etc)I would like to make it so that it can also show all books if "type" isn't selected. I THOUGHT the string would look like this: <asp:SqlDataSource ID="SqlDSBooks" runat="server" ConnectionString="<%$ ConnectionStrings:csK2Reader %>" SelectCommand="SELECT * FROM [Books] ( If @Type <> "" then WHERE ([Type] = @Type)) ORDER BY [SortDate] DESC"> But it doesn't seem to want to work. I get a "server tag is not well formed" error.
I have a table called "member" that has two fields (amongst others) called "firstname" and "city"I want to return a list that sorts people who live in the same city, but does not return people who do not have a city in common.For example if this is my data:Karen - ParisMike - RomeTim - Dallas
Jim - ParisChris - DallasJohn - ManhattanSarah - OrlandoDavid - DallasThe query would return this:Dallas - ChrisDallas - DavidDallas - TimParis - JimParis - KarenI have this SQL so far: Select city, firstname From member Order By city, firstnamebut it includes all the cities including those that only have 1 resident.Can someone tell me how to do this?Thanks a lot,Chris
hi,i have three fields in the database tablep1 p2 rank10% 20% 3 21% 40% 2now i am passing the input as 15%...this 15% is related to 3rd rank.. so i need the o/p rank as 3..if the p1 and p2 datatypes are varchar..then how we can we write the query for that one tgo get the rank as 3.Ramesh
Hi All Can anyone tell me what this simple SQL query would be: Find all the words "black", "dvd" and "player" from any of the fields "Product", "Brand" or "Description".
I am trying to select players from a database based on the userid not having any user's name in it with an order by ASC. I basically want all the players that haven't been taken. Here is what I came up with and it gives me empty.
strSQLA="SELECT UserID, playerName from Allplayers WHERE UserID = '' ORDER BY playername ASC"
I hope it's considered appropriate to post a SQL query question here; it's not I'll gladly post this question elsewhere. That having been said, I've run into a simple but quite tricky SQL query and was wondering if the community might be able to help. Here's what's going on: I have a "Documents" table. Let's call it DI have a "Benefits" table. Let's call it B.There is a many-to-many relationship between D and B so I have a third table to store the relationships. Let's call that table BD. When I create a document it creates a row in D. Let's call that D1, D2...DN. When I create a benefit it creates a row in B. Let's call that B1, B2...BN When I associate a document to a paritcular benefit, let's say that if D1 and B2 are associated, that I created row B2-D1 in my BD table. Now here's what my challenge is. Suppose I have these entries in my tables: D: D1, D2, D3B: B1, B2, B3 Table BD:B1-D1B2-D1B2-D2 When the user goes to add documents to benefit B1, I want to show the user only documents that are not yet added to B1. In this case, I want to show the user D2 and D3 but not D1 since that one's already added. How do I write a SQL query to do this? Here's what I've been using, but it shows too many results (e.g. included D1, D2, D3) SELECT D.*, BD.*FROM Documents AS d LEFT JOIN rel_BenefitsDocuments AS bd ON d.doc_id = bd.doc_idWHERE (benefit_id <> @benefit_id OR benefit_id IS NULL) Any thoughts?
I want to write a sql query for an asp page which will display only unique rows from the specified column along with the number of count for each unique row.
Example:
Table that I want to query
Last Name || First Name Gates || Bill Boyce || Mike Gates || Bill Gates || Phil
Results I want:
Last Name || First Name || Count Gates || Bill || 2 Boyce || Mike || 1 Gates || Phil || 1
I am new to SQL and this question may be most easiest to many of you. Here is what I need.
I have two identical tables (exactly the same in structure) having a compound primary key with a combination of 3 columns. Can someone give me the most efficient query that fetches all the rows from table1 that are not in table2.
from sales_contact sc , invoice i , invoice_line_item il , sales_region_special_section srss , sales_region sr , issue_date idd
where sc.sales_contact_id = i.sales_contact and i.invoice_id = il.invoice and srss.sales_region = sr.sales_region_id and il.issue_date = idd.issue_date_id and srss.invoice_line_item = il.invoice_line_item_id
order by sc.sales_contact_id
================
heres some of the result set I want only the records with the greatest id for each unique sales contact...
AF85F32E-8E34-4C40-9468-00148A34E903, 41, N AF85F32E-8E34-4C40-9468-00148A34E903, 42, N 5D26328A-192B-4E4E-9B34-010C4E077CF8, 77, N 5D26328A-192B-4E4E-9B34-010C4E077CF8, 70, N 5D26328A-192B-4E4E-9B34-010C4E077CF8, 34, BC B44C914E-6001-40CE-8AB6-0126BD572D45, 25, NW B44C914E-6001-40CE-8AB6-0126BD572D45, 26, NW B44C914E-6001-40CE-8AB6-0126BD572D45, 24, NW B44C914E-6001-40CE-8AB6-0126BD572D45, 28, HC B44C914E-6001-40CE-8AB6-0126BD572D45 , 28, NW
this would be an ideal result set using the data above...note there are situtations where there are n* for a greatest issue id.
AF85F32E-8E34-4C40-9468-00148A34E903, 42, N 5D26328A-192B-4E4E-9B34-010C4E077CF8, 77, N B44C914E-6001-40CE-8AB6-0126BD572D45, 28, HC B44C914E-6001-40CE-8AB6-0126BD572D45, 28, NW
This should be easy, I'm just having a brainfart at the moment, can't remember how to do this:
Say I have a bunch of records in a table, with an ID field as Key. I want to return the count of times each ID shows up, so for the following example data:
This should be obvious but for some reason I can't see it.
When this is done I'm going to join in another table to get a name based on the ID with the highest count. I believe it's faster to do a TOP 1 here rather than after the join, but I want to verify that while I'm at it also.
I am a complete newbie to SQL. I have a simple query to make in SQL, but I'm not being able to construct the statement properly. I've already tried googling this info, but with little luck. If someone could help me here, I'd be very thankful.
The problem:
I have a table with a list of questions. All questions have a serial number. The query has to return whether a particular question is the last one in the table or not (according to serial no.)
Logically, this is the query -
Code:
select islast = 0 if count(*) from question where serialno > $serial != 0 else select islast = 1;
The '$serial' part will get replaced dynamically before query execution through another program.
Any idea how to code this in valid SQL? I would like to make it a simple statement and not a stored procedure. Thanks.
Hey.. hope someone can help, i desperatly need some assistance. I have a few query issues but first things first.. one is that i have a table of messages and users having an online conversation, so fields are msg id, subject, topic, message, user, reply to and time it was sent. Im trying to do a query that will tell me which user sent the most messages, ive tried using count and stuff like that but not really getting anywhere. It will basically have to count each time a user has spoken and then give me the name of the user that has sent the most messages, ive been playing around with stuff like SELECT Count(*) AS Expr1 FROM Table1 WHERE User='andro8472' OR User='bumies';
That will count the times those users have spoken but cant get further
any help would be greatly appreciated really stuck at the mo..
I'm having a bad day as I just cannot get a query to work and its doing my head in and it should be a simple query.
I'll try and explain what I need.
Have a simple query with one join, this is it so far:
SELECT DISTINCT Replace(StaffName,'''''',' ') AS StaffName,OutReason,OutStartDate ,OutEndDate,OutStartTime,OutEndTime,OutID FROM vwOutOfOffice LEFT OUTER JOIN vwStaffList ON OutUser=StaffID WHERE OutComplete=0
What I'm having trouble with adding to the WHERE is as follows, I need a list of Staff who are out of the office based on the various criteria:
Example Current date=29/02/2008 Current time=14:00
Start date---End Date----Start Time--End Time--Should Appear 27/02/2008--28/02/2008--09:00------17:00-----No (because of date) 28/02/2008--03/03/2008--08:00------17:00-----Yes 28/02/2008--29/02/2008--17:00------17:00-----Yes 29/02/2008--29/02/2008--12:00------14:00-----Yes 29/02/2008--29/02/2008--14:30------17:00-----No (because of time) 02/03/2008--02/03/2008--08:00------10:00-----No (because of date)
There may be others I've missed but as long as the dates combined with the times match correctly I need the records to appear.
Please help before I end up putting my head through the monitor.
ID Number NameJoin DateSex 101 Jason01/02/1996M 117 Robert06/25/1999M 113 Doug08/12/1999M 161 Marian07/30/1998F
Please let me know the SQL queries for the following questions for the above table:
1)Write a Select statement that selects the persons whose Type is "M" and who have joined in the last four years and place the result in an array. Today's date is 12/31/1999.
2) Write a Select statement that selects the persons who do not have unique ID Number and place the results in an array.
3) Write code to sort the array by Name + Join Date. Assume that the array has already been created and is sorted in the same manner as the table above. The Join Date is of type smalldatetime. The Name field should be sorted case insensitively.