Need To Set A Field In A Select Statement Equal To Yes Or No If Record Exists In Separate Table
Hey gang,
I've got a query and I'm really not sure how to get what I need. I've got a unix datasource that I've setup a linked server for on my SQL database so I'm using Select * From OpenQuery(DataSource, 'Query')
I am able to select all of the records from the first two tables that I need. The problem I'm having is the last step. I need a field in the select statement that is going to be a simple yes or no based off of if a customer number is present in a different table. The table that I need to look into can have up to 99 instances of the customer number. It's a "Note" table that stores a string, the customer number and the sequence number of the note. Obviously I don't want to do a straight join and query because I don't want to get 99 duplicates records in the query I'm already pulling.
Here's my current Query this works fine:
Select *From OpenQuery(UnixData, 'Select CPAREC.CustomerNo, CPBASC_All.CustorCompName, CPAREC.DateAdded, CPAREC.Terms, CPAREC.CreditLimit, CPAREC.PowerNum
From CPAREC Inner Join CPBASC_All on CPAREC.CustomerNo = CPBASC_All.CustomerNo
Where DateAdded >= #12/01/07# and DateAdded <= #12/31/07#')
What I need to add is one more column to the results of this query that will let me know if the Customer number is found in a "Notes" table. This table has 3 fields CustomerNo, SequenceNo, Note.
I don't want to join and select on customer number as the customer number maybe repeated as much as 99 times in the Notes table. I just need to know if a single instance of the customer number was found in that table so I can set a column in my select statement as NotesExist (Yes or No)
Any advice would be greatly appreciated.
View Complete Forum Thread with Replies
Related Forum Messages:
Insert Record Into Temporary Table From A Select Statement
Hi guys, anyone can help me? i using sp to select a select statement from a join table. due to the requirement, i need to group the data into monthly/weekly basic. so i already collect the data for the month and use the case to make a new compute column in the selete statement call weekGroup. this is just a string showing "week 1", "week 2" .... "week 5". so now i want to group the weekgroup and disply the average mark. so i need to insert all the record from the select statement into the temporary table and then use 2nd select statement to collect the new data in 5 record only. may i know how to make this posible? regards terence chua
View Replies !
'One Table' Record To Separate 'two Or Three Tables' Using Cursor?
I would like to 'one table' record to separate 'two or three tables' . I just know use the DTS , try to import and export again and agian. So trouble. Could you give me some suggestions for me? For example , 'Cursor' write in new table . But I try to SQL Server Books Online which is not suitable for me solving problems. One table separate two or three tables. Can you wirte the detail example for me? Thx a lot.
View Replies !
In Code Behind, What Is Proper Select Statement Syntax To Retrieve The @BName Field From A Table?
In Code Behind, What is proper select statement syntax to retrieve the @BName field from a table?Using Visual Studio 2003SQL Server DB I created the following parameter:Dim strName As String Dim parameterBName As SqlParameter = New SqlParameter("@BName", SqlDbType.VarChar, 50) parameterBName.Value = strName myCommand.Parameters.Add(parameterBName) I tried the following but get error:Dim strSql As String = "select @BName from Borrower where BName= DOROTHY V FOWLER " error is:Line 1: Incorrect syntax near 'V'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'V'. Source Error: Line 59: Line 60: Line 61: myCommand.ExecuteNonQuery() 'Execute the query
View Replies !
Trying To Select Info With If Exists Statement With No Avail
Im trying to select rows on the following criteria My app has a user that can have x jobs, each job has related entries which are marked has unread or read. I need to return any jobs that contain any unread entries also I need to return other jobs that have no entries marked as read. I am able to return the following: Comment UnReadMy Job 164 Comment UnReadFor Cam 166 Comment ReadThe Job 157 Comment ReadThird 159 Comment ReadMy Job 164 On Site Visit ReadMy newest job for log test 167 but as you can see jobid 164 appears in both groups and I need it to be one or the other I tried using the if exists statement and was only able to return one group either unread or read, not both. I've tried everything but I'm new and I figure that theres got to be a more elegant way. Heres my sql: CREATE PROCEDURE spGetJobsByUnreadAndReadByUserID @UserID INT AS BEGIN IF EXISTS(SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact, Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who FROM Master_Jobs INNER JOIN Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND Job_Assignments.UserID = Users.UserID WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND BackUp_Read = 'UnRead') BEGIN SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact, Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who FROM Master_Jobs INNER JOIN Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND Job_Assignments.UserID = Users.UserID WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND BackUp_Read = 'UnRead' ORDER BY BackUp_Read ASC END ELSE BEGIN SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact, Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who FROM Master_Jobs INNER JOIN Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND Job_Assignments.UserID = Users.UserID WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND BackUp_Read = 'Read' ORDER BY BackUp_Read ASC END END GO Thanks again
View Replies !
Checking A Table To See If A Record Already Exists
I've got two tables, one containing a list of company names(approx 10,000 records), the other containing a list of company employees (approx 30,000 records) joined by the CompanyID column. I have a third table (approx 700 records) containing new employees to be added to the employee table. Each record in this table has the employees details plus the name of their company. I want to write a query that will check each row in the third table to see if a) the employee exists in the Employees table b) the company exists in the Companies table and c) the employee is listed under the correct company The query should also handle any combination of the above. So if the company doesn't exist but the employee does, create the company on the companies table and update the appropriate record on the employees table with the new CompanyID etc. etc. Oh, forgot to mention. The company names in the third table won't be exactly the same as the ones in the Company table so will need to use CharIndex. Anybody got any ideas?
View Replies !
TSQL - Use ORDER BY Statement Without Insertin The Field Name Into The SELECT Statement
Hi guys, I have the query below (running okay): Code Block SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02' FROM myTables WHERE Conditions are true ORDER BY Field01 The results are just as I need: Field01 Field02 ------------- ---------------------- 192473 8461760 192474 22810 Because other reasons. I need to modify that query to: Code Block SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02' INTO AuxiliaryTable FROM myTables WHERE Conditions are true ORDER BY Field01 SELECT DISTINCT [Field02] FROM AuxTable The the results are: Field02 ---------------------- 22810 8461760 And what I need is (without showing any other field): Field02 ---------------------- 8461760 22810 Is there any good suggestion? Thanks in advance for any help, Aldo.
View Replies !
ASSIGN Record Equal
Good day! I have the qry, which is suppose to assigned records to active user (almost 15 users) equal, but it doesn’t- sometime it assigned more to some users and less to others. How could I modify my qry to make sure it assigns the records equals to each user? Please, see the qry below. I will appreciate any help Thk UPDATE TBLFRAUDFINDER SET DATE_ASSIGNED=GETDATE(), FRAUDANALYSTASSIGNED=@FRAUDANALYST WHERE FRAUDID=@FRAUDID OR (FRAUDANALYSTASSIGNED IS NULL AND ((INQUIRY_GOVT_NUMBER=@INQUIRY_GOVT_NUMBER) OR (CUST_NM=@CUST_NM) OR (ALERT_IDENTIFIER=@ALERT_IDENTIFIER) OR (ACCT IN (SELECT ACCT FROM TBLFRAUDFINDER WHERE INQUIRY_GOVT_NUMBER=@INQUIRY_GOVT_NUMBER OR CUST_NM=@CUST_NM OR ALERT_IDENTIFIER=@ALERT_IDENTIFIER))
View Replies !
Case Statement Within A Select Where 2 Or More Instances Of The Record Exist.
Ok,I have a data warehouse that I am pulling records from using OracleSQL. I have a select statement that looks like the one below. Now whatI need to do is where the astrics are **** create a case statement orwhatever it is in Oracle to say that for this record if a 1/19/2005record exists then End_Date needs to be=1/19/2005 else getEnd_Date=12/31/9999. Keep in mind that a record could have both a1/19/2005 and 12/31/9999 instance of that account record. If 1/19exists that takes presedent if it doesnt then 12/31/9999. The problemis that the fields I pull from the table where the end_date is inquestion change based on which date I pull(12/31/9999 being the mostrecient which in some cases as you see I dont want.) so they are notidentical. This is tricky.Please let me know if you can help.SELECTCOLLECTOR_RESULTS.USER_ID,COLLECTOR_RESULTS.LETTER_CODE,COLLECTOR_RESULTS.ACCT_NUM AS ACCT_NUM,COLLECTOR_RESULTS.ACTIVITY_DATE,COLLECTOR_RESULTS.BEGIN_DATE,COLLECTOR_RESULTS.COLLECTION_ACTIVITY_CODE,COLLECTOR_RESULTS.PLACE_CALLED,COLLECTOR_RESULTS.PARTY_CONTACTED_CODE,COLLECTOR_RESULTS.ORIG_FUNC_AREA,COLLECTOR_RESULTS.ORIG_STATE_NUMBER,COLLECTOR_RESULTS.CACS_FUNCTION_CODE,COLLECTOR_RESULTS.CACS_STATE_NUMBER,COLLECTOR_RESULTS.STATE_POSITION,COLLECTOR_RESULTS.TIME_OBTAINED,COLLECTOR_RESULTS.TIME_RELEASED,COLLECT_ACCT_SYS_DATA.DAYS_DELINQUENT_NUM,sum(WMB.COLLECT_ACCT_SYS_DATA.PRINCIPAL_AMT)As PBal,FROMCOLLECTOR_RESULTS,COLLECT_ACCT_SYS_DATA,COLLECT_ACCOUNTWHERECOLLECT_ACCOUNT.ACCT_NUM=COLLECT_ACCT_SYS_DATA.ACC T_NUM(+)ANDCOLLECT_ACCOUNT.LOCATION_CODE=COLLECT_ACCT_SYS_DAT A.LOCATION_CODE(+)AND COLLECT_ACCOUNT.ACCT_NUM=COLLECTOR_RESULTS.ACCT_NU M(+)AND COLLECT_ACCOUNT.LOCATION_CODE=COLLECTOR_RESULTS.LO CATION_CODE(+)AND COLLECTOR_RESULTS.ACTIVITY_DATE =to_date(''01/19/2005'',''mm/dd/yyyy'')AND COLLECT_ACCOUNT.END_DATE = to_date(''12/31/9999'',''mm/dd/yyyy'')AND COLLECT_ACCT_SYS_DATA.END_DATE = *****************
View Replies !
The Select Statement Is In A Field
Ok, I inherited this database and there is a field that stopres a selectstatement. Is there anyway possible to execute the value of the fieldwithin a select statement?For example:the table:Name "george"lookupForName "Select orders from Ordertable"So maybe something like select name, execute(lookupforname) as ordersSorry, I didn't design this, just inherited :)george
View Replies !
Select Statement With A New Identity Field
Hello, Is it possible to generate a identityfield dynamically upon select, like this: SELECT tempID AS identity(1,1), username FROM table1 ORDER BY username ASC I want the output to be: 1 - Name12 - Name23 - Name3 The reason for this, is that i want to change the sort order in many diffrent ways, but i need to get the IDs from 1-?? even when the sort order changes. Like: SELECT tempID AS identity(1,1), username FROM table1 ORDER BY username DESC I want the output to be: 1 - Name32 - Name23 - Name1 Patrick
View Replies !
Query To Sum The Same Field Twice In The Select Statement
Hello friends , I have table (MoneyTrans) with following structure [Id] [bigint] NOT NULL, [TransDate] [smalldatetime] NOT NULL, [TransName] [varchar](30) NOT NULL, -- CAN have values 'Deposit' / 'WithDraw' [Amount] [money] NOT NULL I need to write a query to generate following output Trans Date, total deposits, total withdrawls, closing balance i.e. Trans Date, sum(amount) for TransName='Deposit' and Date=TransDate , sum(amount) for TransName=Withdraw and Date=TransDate , Closing balance (Sum of deposit - sum of withdraw for date < = TransDate ) I am working on this for past two days with out getting a right solution. Any help is appreciated Sara
View Replies !
Select Statement Eliminate Field Name
Hi I have tabelA, Which has 10 columns, I need to select 10 column values only no field names. Is there any way I can select only table values not field names. I don't want to see field name in my query result set. Please let me know. I appreciate your help. Thanks Regards -Leong
View Replies !
How Do I Call A Select Statement Properly When The Field Is A Yes/no?
Hello, i am pretty new to asp. I am trying to do a select statement for sending an email to everyone who is not an admin. the code is below, i know it must be fairly simple, yet i do not know how to do it. With the code below, I select everyone. I want to know how to do it properly, similar to the second which does not work. Dim cmd As New OleDbCommand("SELECT Username, Pass, Gender, FirstName, LastName, Email, NickName FROM tblUsers", conn) DOES NOT WORK: Dim cmd As New OleDbCommand("SELECT Username, Pass, Gender, FirstName, LastName, Email, NickName FROM tblUsers WHERE Admin = 'N'", conn) Thanks in advance.
View Replies !
SELECT Statement - How To Not Get Column Field Names?
I do a SELECT * from table command in an ASP page to build a text fileout on our server, but the export is not to allow a field name rows ofrecords. The first thing I get is a row with all the field names. Whydo these come in if they are not part of the table records? How do Ieliminate this from being produced? Here's the ASP code....<html><head><title>Package Tracking Results - Client Feed</title></head><body><%' define variablesdim oConn ' ADO Connectiondim oRSc ' ADO Recordset - Courier tabledim cSQLstr ' SQL string - Courier tabledim oRSn ' ADO Recordset - NAN tabledim nSQLstr ' SQL string - NAN tabledim objFSO ' FSO Connectiondim objTextFile ' Text File' set and define FSO connection and text file object locationSet objFSO = CreateObject("Scripting.FileSystemObject")'Set objTextFile =objFSO.CreateTextFile(Server.MapPath("textfile.txt"))'Response.Write (Server.MapPath("textfile.txt") & "<br />")Set objTextFile = objFSO.OpenTextFile("C: extfile.txt",2)' write text to text file'objTextFile.WriteLine "This text is in the file ""textfile.txt""!"' SQL strings for Courier and NAN tablescSQLstr = "SELECT * FROM Courier"' set and open ADO connection & oRSc recordsetsset oConn=Server.CreateObject("ADODB.connection")oConn.Open "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" &"c:/Database/QaTracking/QaTracking.mdb" & ";"set oRSc=Server.CreateObject("ADODB.Recordset")oRSc.Open cSQLstr, oConnResponse.ContentType = "text/plain"Dim i, j, tmpIf Not oRSc.EOF ThenFor i = 1 To oRSc.Fields.CountobjTextFile.Write oRSc.Fields(i-1).NameIf i < oRSc.Fields.Count ThenobjTextFile.Write " "End IfNextobjTextFile.WriteLineWhile Not oRSc.EOFFor i = 1 To oRSc.Fields.CountIf oRSc.Fields(i-1) <"" Thentmp = oRSc.Fields(i-1)' If TypeName(tmp) = "String" Then' objTextFile.Write "" &_'Replace(oRSc.Fields(i-1),vbCrLf,"") & ""' ElseobjTextFile.Write oRSc.Fields(i-1)' End IfEnd IfIf i < oRSc.Fields.Count ThenobjTextFile.Write " "End IfNextobjTextFile.WriteLineoRSc.MoveNextWendEnd IfobjTextFile.CloseSet objTextFile = NothingSet objFSO = NothingoRSc.CloseSet oRSc = NothingoConn.CloseSet oConn = Nothing%></body></html>
View Replies !
Select Statement With Run Time Field Selection
I have this SELECT statement. SELECT [issueID], [name] FROM [MyIssue] What I wanted to do is in addition to the above statement, I want to add two run time fields like this: 99 [issueID],'All Issues' [name] So let's say the above select statements generates this list: Summer 2007 Issue Winter 2007 Issue The two addition fields will make the result list like this: 01 Summer 2007 Issue 02 Winter 2007 Issue 99 All Issues How do I accomplish this? Any help is much appreciated.
View Replies !
Convert A Time Field In The Select Statement Of The Query
Hi, I have a field called "Starting DateTime" and I want to convert into my local time. I can convert it in the report with the expression "=System.TimeZone.CurrentTimeZone.ToLocalTime(Fields!Starting_DateTime.Value)", but that is too late. I want to convert it in the Select statement of the query. Can anyone help me please? Thx
View Replies !
Trying To Identify A Unique Record On Two Separate Tables
Hello, I am working with a database that among other things uses multipart keys as the unique indexes which are not consistent from say one table where a parent record resides to another table which contains related child records. For example I am working with two tables right now, one that contains content that I'll call Contents and the other which contains Usage information about the contents (number of view, a rating and comments give by a customer) which I'll call ContentsUsage. The system that manages the data for the tables has a versioning system by which, whn a content item is added (first time) a "unique" id (guid) and a version number of 1 is created along with the rest of data items in the Contents table and likewise in the ContentsUsage table (essentially a one to one mapping) on the like named fields in that table. Now, each time a given record in the Contents table is updated a new version, with the same guid is created in the Contents and ContentsUsage table. So one side I have:ContentGUID > AAAAVersion > 1ContentGUID > AAAAVersion > 2And the other table (ContentsUsage)ContentGUID > AAAAVersion > 1ContentGUID > AAAAVersion > 2 While both of these tables have a quasi-unique record (row_id) of type char and stored as a guid neither obviously are the same in the two tables and having reviewed the database columns for these tables I find that the official unique key's for these tables are different (table 1, Contents combines the ContentGUID and Version) as the composite / mutli-key index, while table ContentsUsage uses the RowGUID as it's unique index. Contents RowGUID (unique key)ContentGUIDVersionViewsRatingComments................RowGUID ContentGUID (unique key)Version (unique key)Description..... Bearing this in mind I am unable of course to link directly the two tables by using the just the ContentGUID and have to combine the additional Version to I believe obtain the actual "unique" record in question. The question is in terms of writing queries, what would the most efficient query be? What would be the best way to join the two in a query? And are there any pitfalls with the current design that you can see with the way this database (or specifically these tables are defined)? It's something I inherited, so fire away at will on the critique. Having my druthers I would have designed these tables using a unique key of type int that was autogenerated by the database. Any advice, thoughts or comments would be helpful. Thanks,P.
View Replies !
Inserting A Record For Each Separate Aggregate (solved)
Hi,As I wrote my message the solution came to me, so I thought I wouldpost anyway for others to see in case it was useful:Here is some sample DDL for this question:CREATE TABLE Source (my_value INT NOT NULL )GOINSERT INTO Source VALUES (1)INSERT INTO Source VALUES (2)INSERT INTO Source VALUES (3)GOCREATE TABLE Destination (value_type VARCHAR(10) NOT NULL,value INT )GOI would like to fill the destination with a row for the COUNT, SUM,MIN, and MAX. My own problem is of course much more complex than this,but this is the basic stumbling block for me now. So, the rows that Iwould expect to see in Destination are:value_type value---------- -----COUNT 3SUM 6MIN 1MAX 3The solution that I came up with was to add a Value_Types table:CREATE TABLE Value_Types (value_type VARCHAR(10) NOT NULL )GOINSERT INTO Value_Types VALUES ('COUNT')INSERT INTO Value_Types VALUES ('SUM')INSERT INTO Value_Types VALUES ('MAX')INSERT INTO Value_Types VALUES ('MIN')GONow the SQL is pretty simple:SELECT V.value_type,CASE V.value_typeWHEN 'COUNT' THEN COUNT(*)WHEN 'SUM' THEN SUM(S.my_value)WHEN 'MAX' THEN MAX(S.my_value)WHEN 'MIN' THEN MIN(S.my_value)ENDFROM Source SINNER JOIN Value_Types V ON 1=1-Tom.P.S. - I know that I did not include primary or foreign keys in my DDL.I'll leave it as an excercise to the reader to figure those out. Ithink the code adequately explains the concept.
View Replies !
How To Select Record Only In One Table?
Hello, everyone: I have two tables like: Table A IDCodeANumA 1D1289 2C4300 3C9409 Table B IDCOdeBNumB 1D3266 2C4300 3C7101 How to find out the records that is in Table A not in Table B, and in Table B not in Table A? That means C4/300 should not be selected. Thanks ZYT
View Replies !
How Can I Select Nth Record In A Table.
hi friends, I am having a table with student marks in that i need to select a student who is the 5 th rank based on total marks obtained by the student.how can write sql for that. name, totmarks ----------------- kumar 145 ravi 300 jude 189 geeetha 320 rajesh 251 guru 190 ramesh 99 ---------------------- i am having records like this.pl help me. thank u regards raj
View Replies !
Trying To Return A Single Record For Each Client From Child Table Based Upon A Field Of Date Type In Child Table
I have table "Clients" who have associated records in table "Mailings" I want to populate a gridview using a single query that grabs all the info I need so that I may utilize the gridview's built in sorting. I'm trying to return records containing the next upcoming mailing for each client. The closest I can get is below: I'm using GROUP BY because it allows me to return a single record for each client and the MIN part allows me to return the associated record in the mailings table for each client that contains the next upcoming 'send_date' SELECT MIN(dbo.tbl_clients.client_last_name) AS exp_last_name, MIN(dbo.tbl_mailings.send_date) AS exp_send_date, MIN(dbo.tbl_mailings.user_id) AS exp_user_id, dbo.tbl_clients.client_id, MIN(dbo.tbl_mailings.mailing_id) AS exp_mailing_idFROM dbo.tbl_clients INNER JOIN dbo.tbl_mailings ON dbo.tbl_clients.client_id = dbo.tbl_mailings.client_idWHERE (dbo.tbl_mailings.user_id = 1000)GROUP BY dbo.tbl_clients.client_id The user_id set at 1000 part is what makes it rightly pull in all clients for a particular user. Problem is, by using the GROUP BY statement I'm just getting the lowest 'mailing_id' number and NOT the actual entry associated with mailing item I want to return. Same goes for the last_name field. Perhaps I need to have a subquery within my WHERE clause?Or am I barking up the wrong tree entirely..
View Replies !
Select Most Recent Customer Record From Table Only?
If I have a table structure similar to the following, how might I query it to obtain the Transaction ID, Transaction Date, and Customer Name for the most recent transaction per customer only: TransactionTable: TransactionID TransactionDate TransactionType CustomerName 1 10/1/07 1 Bob 2 8/30/07 2 Janet 3 9/17/07 1 Mike 4 9/25/07 1 Bob The following query will return all records in the table other than Janets...not what I want: SELECT Transaction ID, TransactionDate, CustomerName FROM TransactionTable WHERE TransactionType = 1 ORDER BY TransactionDate DESC The following query will return all records in the table other than Janets again, because DISTINCT will use the combo of TransactionID, TransactionDate, and Customer name for uniqueness...not what I want: SELECT DISTINCT Transaction ID, TransactionDate, CustomerName FROM TransactionTable WHERE TransactionType = 1 ORDER BY TransactionDate DESC The results set I'm looking for would be the following, where only the most recent entry per customer with TransactionType 1 is returned (i.e. one record for Bob): TransactionTable: TransactionID TransactionDate CustomerName 1 10/1/07 Bob 3 9/17/07 Mike I believe I need an appropriate subquery to yield the results I desire, but can't sort out what it is? I do not want to execute multiple queries but subqueries are fine. Unfortunately there's probably an easy answer that my brain is not currently generating. Any help would be appreciated. Note, this is not a real table, but a sample to illustrate the concept for the query I need. Thanks.
View Replies !
How To Show Two Dataset With Equal && Non Equal Of Multiple Selection.
Dear Friends, In my report, I am having Listbox for users to choose Country, City & Company. The user can choose Country. Based on the country selection, cities will be listed out. Based on the city selection, Companies will be listed out. They can choose companies. Now, I have to show two set of results. A. List of Companies as per selection ( dataset with equal to selection ) B. List of Companies which are not selected ( ie dataset with not equal to selection ) I have created a dataset with all companies and filter it by selection. When I tried with the filter option in the Dataset, I am able to check for only one value and not for multiple value. If the selection is one company, then I can filter it. But if they choose 5 companies, I am not not able to filter it. Is there any other option I can try out. Please advice. Thanks. warm regards Rakin Singapore.
View Replies !
Separate Data In One Field
I recieved a SQL Server table that was supposed to have just the firstname in a field, but actually has firstname and middle name. Example David Michael Carol Anne Is there a way in a query to look for the blank space and separate the names?
View Replies !
Error (8626) While Inserting Record Into Table With Text Field And Which Is The Base For Indexed View
I have a problem with inserting records into table when an indexed viewis based on it.Table has text field (without it there is no problem, but I need it).Here is a sample code:USE testGOCREATE TABLE dbo.aTable ([id] INT NOT NULL, [text] TEXT NOT NULL)GOCREATE VIEW dbo.aViewWITH SCHEMABINDING ASSELECT [id], CAST([text] AS VARCHAR(8000)) [text]FROM dbo.aTableGOCREATE TRIGGER dbo.aTrigger ON dbo.aView INSTEAD OF INSERTASBEGININSERT INTO aTableSELECT [id], [text]FROM insertedENDGODo the insert into aTable (also through aView).INSERT INTO dbo.aTable VALUES (1, 'a')INSERT INTO dbo.aView VALUES (2, 'b')Still do not have any problem. But when I need index on viewCREATE UNIQUE CLUSTERED INDEX [id] ON dbo.aView ([id])GOI get following error while inserting record into aTable:-- Server: Msg 8626, Level 16, State 1, Procedure aTrigger, Line 4-- Only text pointers are allowed in work tables, never text, ntext, orimage columns. The query processor produced a query plan that requireda text, ntext, or image column in a work table.Does anyone know what causes the error?
View Replies !
How To Know If A Record Exists
Hello,I have a TextBox and an Insert Button, it works like this: protected void Button1_Click(object sender, EventArgs e) { String strConn=SqlDataSource1.ConnectionString; SqlCommand cmd = new SqlCommand("INSERT INTO My_Table_1 (Column_1) VALUES ("+TextBox1.Text+")", new SqlConnection(strConn)); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } But, what code i must write for checking, if the value i am trying to insert already exists ??I mean something like this:if (TextBox1.Text does not Exists on any Record in My_Table_1) then Insert itelse Show Message : "Already exists a record with this value"Thank you SO MUCH, guys,Carlos.
View Replies !
IF NOT EXISTS (... - EXISTS TABLE : Nested Iteration. Table Scan.Forward Scan.
Hi, This is on Sybase but I'm guessing that the same situation would happen on SQL Server. (Please confirm if you know). I'm looking at these new databases and I'm seeing code similar to this all over the place: if not exists (select 1 from dbo.t1 where f1 = @p1) begin select @errno = @errno | 1 end There's a unique clustered in dex on t1.f1. The execution plan shows this for this statement: FROM TABLE dbo.t1 EXISTS TABLE : nested iteration. Table Scan. Forward scan. Positioning at start of table. It's not using my index!!!!! It seems to be the case with EXISTS statements. Can anybody confirm? I also hinted to use the index but it still didn't use it. If the existence check really doesn't use the index, what's a good code alternative to this check? I did this and it's working great but I wonder if there's a better alternative. I don't really like doing the SET ROWCOUNT 1 and then SET ROWCOUNT 0 thing. SELECT TOP 1 won't work on Sybase, :-(. SET ROWCOUNT 1 SELECT @cnt = (SELECT 1 FROM dbo.t1 (index ix01) WHERE f1 = @p1 ) SET ROWCOUNT 0 Appreciate your help.
View Replies !
Check If Record Exists
Hi, I was wondering if someone can help. In vb.net what is the best way to check if a record exists if you are using an sql data reader? For my application I need to display a button control (make it visible on the page) if a record is available after executing my sql select statement. cheers Mark :)
View Replies !
Check If Record Exists
Hello,I created the following SQL script to check if a record exists:IF (EXISTS (SELECT LevelName FROM dbo.by27_Levels WHERE LOWER(@LevelName) = LOWER(LevelName))) Return (1)ELSE Return (0)And I also found in a web page another solution:IF EXISTS(SELECT 1 FROM TABLENAME WHERE LevelName=@LevelName) SELECT 1ELSE SELECT 0- Which approach should I use?- Why "SELECT 1 FROM"?- And when should I use SELECT or RETURN?All I need is to know if the record exists ... nothing else.I will use this procedure on an ASP.NET 2.0 / C# web site.I am not sure if this important but anyway ...Thank You,Miguel
View Replies !
Don't Insert If Record Exists
/*if key values exist don't insert new record*/ SELECT /*if exists don't insert*/ CASE WHEN ISNULL(gradeId, -1) = -1 THEN INSERT INTO tblScores (gtStudentId, assignmentId, score) VALUES (@nStudent, @nAssignment, 0) END FROM tblScores WHERE gtStudentId = @nStudent AND assignmentId = @nAssignment tblScores has two fields comprising its primary key (gtStudentId, assignmentId) and the gradeId field is a required filed in this table. I'm getting syntax errors when I click check syntax (near keywords insert from and end). one other note: this CASE END is nested inside a BEGIN END loop, is this the problem? Is the 'End" of the 'Case' closing the 'End' of the 'Begin'? thanks
View Replies !
Insert Record If None Exists
Hello folks, I am new to msSQL and ASP, I need some help writing an SQL statement that will first check to see if a combination or record exists, if none found thant it will add it. I am working a section of a site that adds favorites to the database. Each user can have more that one favorite hence it has to check for that unique combination of the fields, UserID and FavID My Code: Dim objConnection, objRecordset, strSQL Dim strFavID, strUserID strFavID = request.Form("favid") strUserID = request.Form("userid") Set objConnection = Server.CreateObject("ADODB.Connection") Set objRecordset = Server.CreateObject("ADODB.Recordset") objConnection.Open Application("ConnectionString") strSQL = "INSERT INTO FAV (UserID,FavID) (SELECT DISTINCT " & strUserID & " AS UserID " & _ strFavID & " AS FavID" & " FROM FAV)" & _ " WHERE " & strUserID & " & " & strFavID & " NOT IN (SELECT UserID, FavID FROM FAV)" response.Write(strSQL) 'response.End() If strFavID <> "" Then On Error Resume Next objConnection.Execute(strSQL) objConnection.Close Set objConnection = Nothing End If This code is giving me a syntax error, how do I write the correct statement. I am using MS Access 2k Thanks for your help
View Replies !
Splitting One Data Field With Hyphens To Separate Records
I receive a file that will have hyphens between data items such as 123-aed-edr-45r-ui9 1-ed3-45r-rrr-98u I need to split the values to load into a table that will hold the 5 separate data itens. The fields will always have the hyphens but could be different lengths. Any idea on a best approach to split this in tsql
View Replies !
Select The Insert Value Into Field In Another Table!!!!!!
i have tbl_location which includes userid, building, room. i combine the building and room into one feild called mailstop SELECT Userid, Building +'/'+Room AS mailstop FROM tbl_Location i then want to take this recordset and insert it into a field called mailstop in my employee table. but they must based upon the userid of the location table and the userid of the employee table. so the userid of the location table must match the userid of the employee table and insert that mailstop value into the mailstop feild in employee table. i want to get this right the first time. any help would be greatly appreciated.
View Replies !
SELECT Table Field Names
I need a statement or sp that will display, for a given user database, an individual table's fieldnames, datatype, and length. Any help is appreciated. Randy
View Replies !
Referencing A Field In Another Table Within A SELECT
I have a SELECT line in an UPDATE query that looks like this: UPDATE Terms SET Field1 = LEFT(Emp_SSN,9), Field2 = Health, Field3 = (SELECT Emp_PayCode FROM Rates WHERE Health = ID) FROM Inserted,Rates WHERE Terms.Field1 = Emp_SSN On the Field3 update, how do I evaluate Emp_PayCode. Emp_PayCode is a field in another table (Employees). The value of that field is Instructional24 and if I hard code that value into the SELECT line, it works fine and returns the value ($0.00).
View Replies !
Looking For Field Name From Table On Select Criteria
Hari writes "Sub:- looking for Field name from table on select criteria dear friends I have an table [assosories] which have 100 fields. initial 10 fields have some date, varchar, int types rest 90 are bool type. for a single row I need to know the field name which have true vaules in rest 90 fields I need to insert this field name into another table as a row. Thanks HARI"
View Replies !
How To Select Field Names Of Table?
Can someone write a query that select all the fields of tables in database that have type 'image'? Something like this: Select TableName, FieldName FROM TableWhereTheyKeepThoseThings WHERE TableWhereTheyKeepThoseThings.FieldType='Image' ... olny it should work :)
View Replies !
Help With Select Statement - From XML Table
I'm trying to get the <Title> node value returned in the select statement below, but cant quite get it to work. I have the <ID> node being returned in the statement, but not the title. Any help is apprecited. param ids = '<Collection><Content><ID>1</ID><Title>Document 1</Title></Content>< Content><ID>2</ID><Title>Document 2</Title></Content></Collection>' CREATE PROCEDURE [GetDownloads](@Ids xml) AS DECLARE @ResearchDocuments TABLE (ID int) INSERT INTO @ResearchDocuments (ID) SELECT ParamValues.ID.value('.','VARCHAR(20)') FROM @Ids.nodes('/Collection/Content/ID') as ParamValues(ID) SELECT * FROM research_downloads INNER JOIN @ResearchDocuments rd ON research_downloads.doc_id = rd.ID Where research_downloads.post_sf = 0
View Replies !
|