I want to perform a update then select the result. I don't want anything to be able to update the row I am updating until after the select has occurred. How would I do this?
Hi guys..
The question im struggling with is this:
i have a list of helicopter names in different charters and i need to find out WHICH helicopter has the least amount of charters booked. Once i find that out i need to ONLY display the one that has the least.
I so far have this:
SELECT Helicopter_Name COUNT (Distinct Charter_NUM)
FROM Charter_Table
GROUP BY Helicopter Name
^ this is where i am stuck, i realise MIN could be used to pick out the value that is the smallest but i am not sure how to integrate this into the command.
Something like Where MIN = MIN Value
Id really appreciate it
Hi All,
I have a stored proc (SS2008) that takes a couple int ids and needs to look up if they exist in a table before adding a record. I have an int output param I would like to return and set its value based on what occrured. I have this so far, but it always returns 1. Can someone point me in the right direction?
BEGIN TRY
IF EXISTS
(
SELECT * FROM tbMap WHERE (cId= @CId)
)
SET @result = -1; -- This C User is already mapped
ELSE IF EXISTS
(
SELECT * FROM tbMap WHERE (dId = @DId)
)
SET @result = -2; -- This D User is already mapped
ELSE
INSERT INTO tbMap (
Login
, Email
, UserName
, CId
, DId)
SELECT
@UserName
, usr.EmailAddress
, usr.UserName
, @CId
, @DId
FROM tbUser usr WHERE usr.iUserID = @DId
SET @result = 1;
RETURN
END TRY
What am I missing? Thanks for any tips.
Cheers,
~ck in San Diego
SELECT Transactions.TransactionNumber
FROM Transactions
WHERE (((Transactions.Date)>=#11/23/12#)) AND (((Transactions.Date)<=#11/23/12#));
The above code returns all the transaction that happened between the specified dates. But I want those dates to be defined by the user every time the query is executed.
I tried using the [] operators to have the user define the criteria in the WHERE, something like this:
WHERE (((Transactions.Date)>=[Input a Date])) AND (((Transactions.Date)<=[Input a Date]));
But microsoft Access throws a Syntax error message. The same happens when I include the # (date operators) like this
WHERE (((Transactions.Date)>=#[Input a Date]#)) AND (((Transactions.Date)<=#[Input a Date]#));
Is there anopther way to manage dates that I'm not aware of or is asking a user for dates in a query out of the question
var result = (
from contact in db.Contacts
where contact.ContactID == id
join referContactID in db.ContactRefferedBies on contact.ContactID equals referContactID.ContactID
join referContactName in db.Contacts on contact.ContactID equals referContactID.ContactID
orderby contact.ContactID descending
select new ContactReferredByView
{
ContactReferredByID = referContactID.ContactReferredByID,
ContactReferredByName = referContactName.FirstName + " " + referContactName.LastName
}).Single();
Problem is in this line:
join referContactName in db.Contacts on contact.ContactID equals referContactID.ContactID
where referContactID.ContactID is called from the above join line. How to nest these two joins?
Thanks in advance!
Ile
I have the concept of valid/ordered transitions. So for example, it's not possible to move to status In progress from status Complete.
Current and Next in table StatusTransition are FK (StatusType.Id).
The Linq generator has created the following relations:
Child Property Name: StatusTransitions1
Parent Property Name: StatusType1
Participating Properties: StatusType.Id -> StatusTransition.Next
Child Property Name: StatusTransitions
Parent Property Name: StatusType
Participating Properties: StatusType.Id -> StatusTransition.Current
I'm normally ok with Linq but I'm having difficulty getting the list of valid Next StatusTypes from the Current status.
public List<StatusType> GetValidStatusTransitions(int statusId)
{
// trying to write something like the following
// (obviously not correct)
return _statusRepository
.Where(s => s.Id == statusId)
.Next.StatusTypes;
}
Have a lot of unnecessary results using contains() method in my query. Don't tell me to use like or something else. It is hardcoded and couldn't be changed.
Very strange situation here: I'm using L2S to populate a DataGridView.
Code follows:
private void RefreshUserGrid()
{
var UserQuery = from userRecord in this.DataContext.tblUsers
orderby userRecord.DisplayName
select userRecord;
UsersGridView.DataSource = UserQuery;
//I have also tried
//this.UserBindingSource.DataSource = UserQuery;
//UsersGridView.Datasource = UserBindingSource;
UsersGridView.Columns[0].Visible = false;
}
Whenever I use L2S to Add/Delete records from the database, the GridView refreshes perfectly well.
However, if someone is editing the grid and makes a mistake, I want them to be able to hit a refresh button and have their mistakes erased by reloading from the datasource.
For the life of me, I can't get it to work.
The code I am currently using on my refresh button is this:
private void button1_Click(object sender, EventArgs e)
{
this.DataContext.Refresh(RefreshMode.OverwriteCurrentValues);
RefreshUserGrid();
}
But the damn GridView remains unaffected. All that happens is the selected row becomes unselected.
I have tried .Refresh(), .Invalidate(), I've tried changing the DataSource to NULL and back again (all suggestions from similar posts here)....none of it works. The only time the Grid refreshes is if I restart the app.
I must be missing something fundamental, but I'm totally stumped and so are my colleagues.
Any ideas?
Thanks!
Update Combined column using CategoryCode of every OrderId. In this example there are two OrderIds 990 and 986. Need to concatenate categories of these two individually.
The desired result is like this.
990 Bus, Pub, Shoot, Club, Bus, Hos
Thanks.
I have one table, which has three fields and data.
Name , Top , Total
cat , 1 , 10
dog , 2 , 7
cat , 3 , 20
horse , 4 , 4
cat , 5 , 10
dog , 6 , 9
I want to select the record which has highest value of Total for each Name, so my result should be like this:
Name , Top , Total
cat , 3 , 20
horse , 4 , 4
Dog , 6 , 9
I tried group by name order by total, but it give top most record of group by result. Can anyone guide me, please?
I'd like to do had a dynamic number of one start/end time pairs passed to a function as an input parameter. The function would then use the list instead of just one start, and one end time in a select statement.
CREATE FUNCTION [dbo].[GetData]
(
@StartTime datetime,
@EndTime datetime
)
RETURNS int
AS
BEGIN
SELECT @EndTime = CASE WHEN @EndTime > CURRENT_TIMESTAMP THEN CURRENT_TIMESTAMP ELSE @EndTime END
DECLARE @TempStates TABLE
(StartTime datetime NOT NULL
, EndTime datetime NOT NULL
, StateIdentity int NOT NULL
)
INSERT INTO @TempStates
SELECT StartTime
, EndTime
, StateIdentity
FROM State
WHERE StartTime <= @EndTime AND EndTime >= @StartTime
RETURN 0
END
If I have a table structure like this:
Transaction [TransID, ...]
Document [DocID, TransID, ...]
Signer [SignerID, ...]
Signature [SigID, DocID, SignerID, ...]
And the business logic is like this:
Transactions can have multiple documents
Documents can have multiple signatures
And the same signer can
have multiple signatures in
multiple documents within the
same transaction
So, now to my actual question:
If I wanted to find all the documents in a particular transaction, would it be better, performance-wise, if I also stored the TransID and the DocID in the Signer table as well so I have smaller joins. Otherwise, I'd have to join through the Signature Document Transaction Documents to get all the documents in the transaction for that signer.
I think it's really messy to have that many relationships in the Signer table though and it doesn't seem "correct" to do it that way (also seems like an update nightmare) but I can see that it might be better performance for direct joins. Thoughts?
TIA!
I have two tables: Standards and Service Offerings. A Standard can have multiple Service Offerings. Each Standard can have a different number of Service Offerings associated to it.
What I need to be able to do is write a view that will return some common data and then list the service offerings on one line. For example:
Standard Id | Description | SO #1 | SO #2 | SO #3 | ... | SO #21 | SO Count
1 | One | A | B | C | ... | G | 21
2 | Two | A | | | ... | | 1
3 | Three | B | D | E | ... | | 3
I have no idea how to write this. The number of SO columns is set to a specific number (21 in this case), so we cannot exceed past that.
Any ideas on how to approach this?
A place I started is below. It just returned multiple rows for each Service Offering, when they need to be on one row.
SELECT *
FROM SERVICE_OFFERINGS
WHERE STANDARD_KEY IN (SELECT STANDARD_KEY
FROM STANDARDS)
Here is some sample code that inserts a record into a db table:
Dim ds As DataSet = New DataSet()
da.Fill(ds, "Shippers")
Dim RowDatos As DataRow
RowDatos = ds.Tables("Shippers").NewRow
RowDatos.Item("CompanyName") = "Serpost Peru"
RowDatos.Item("Phone") = "(511) 555-5555"
ds.Tables("Shippers").Rows.Add(RowDatos)
Dim custCB As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Update(ds, "Shippers")
It inserts a row in the Shippers Table, the ShippersID is
a Indentity value. My question is how can i retrieve the
Identity value generated when the new row is inserted in
the Shippers table.
I have done several web searches and the sources I've seen on the net don't answer it speccifically or go on to talk about stored procedures. Any help would be appreciated. Thanks!
Hi, i am modifying a plugin slightly to meet my needs, and need to change this query to return post ID's of just one category. I know it has something to do with INNER JOIN, but cant get the query right.
Here is the original query
$query = "SELECT ID as PID FROM $wpdb->posts";
$results = $wpdb->get_results($querydetails,ARRAY_A);
Hello everyone,
I want to count the number of accounts from the resulting table generated from this code. This way, I know how many people liked blue at one time.
Select Distinct PEOPLE.FullName, PEOPLE.FavColor From PEOPLE
Where FavColor='Blue'
Lets say this is a history accounting of what people said their favorite color when they were asked so there may be multiple records of the same full name if asked again at a much later time; hence the distinct.
The code I used may not be reusable in your answer so feel free to use what you think can work. I am sure I found a possible solution to my problem using declare and if statements but I lost that page... so I am left with no solution. However, I think there is a way to do it without using conditionals which is what I am asking and rather have. Thanks.
Edit: My question is: From the code above, is there a way to count the number of accounts in the resulting table?
I have a table named tblItemResources in which I want to get the only 2 rows from each unique field in a column named effectiveDate (order by: ascending):
tblItemResources Table
| empID | effectiveDate | Company | Description
| 0-123 | 2014-01-23 | DFD Comp | Analyst
| 0-234 | 2014-01-23 | ABC Comp | Manager
| 0-222 | 2012-02-19 | CDC Comp | Janitor
| 0-213 | 2012-03-13 | CBB Comp | Teller
and so on.
Any help would be much appreciated.
What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:
INSERT INTO some_table (column1, column2, column3)
SELECT
Rows.n.value('(@column1)[1]', 'varchar(20)'),
Rows.n.value('(@column2)[1]', 'nvarchar(100)'),
Rows.n.value('(@column3)[1]', 'int'),
FROM @xml.nodes('//Rows') Rows(n)
However I find that this is getting very slow for even moderate size xml data.
Given two tables (the rows in each table are distinct):
1) x | y z 2) x | y z
------- --- ------- ---
1 | a a 1 | a a
1 | b b 1 | b b
2 | a 1 | c
2 | b 2 | a
2 | c 2 | b
2 | c
Is there a way to select the values in the x column of the first table for which all the values in the y column (for that x) are found in the z column of the second table?
In case 1), expected result is 1. If c is added to the second table then the expected result is 2.
In case 2), expected result is no record since neither of the subsets in the first table matches the subset in the second table. If c is added to the second table then the expected result is 1, 2.
I've tried using except and intersect to compare subsets of first table with the second table, which works fine, but it takes too long on the intersect part and I can't figure out why (the first table has about 10.000 records and the second has around 10).
EDIT: I've updated the question to provide an extra scenario.
Hi,
I’m going to calculate a ratio between two entities but are having some trouble with the query.
The principal is the same to, say a forum, where you say:
A user gets points for every new thread. Then, calculate the ratio of points for the number of threads.
Example:
User A has 300 points. User A has started 6 thread. The point ratio is: 50:6
My schemas look as following:
student(studentid, name, class, major)
course(courseid, coursename, department)
courseoffering(courseid, semester, year, instructor)
faculty(name, office, salary)
gradereport(studentid, courseid, semester, year, grade)
The relations is a following:
Faculity(name) = courseoffering(instructor)
Student(studentid) = gradereport (studentid)
Courseoffering(courseid) = course(courseid)
Gradereport(courseid) = courseoffering(courseid)
I have this query to select the faculty names there is teaching one or more students:
SELECT COUNT(faculty.name) FROM faculty, courseoffering, gradereport, student WHERE faculty.name = courseoffering.instructor AND courseoffering.courseid = gradereport.courseid AND gradereport.studentid = student.studentid
My problem is to find the ratio between the faculty members salary in regarding to the number of students they are teaching.
Say, a teacher get 10.000 in salary and teaches 5 students, then his ratio should be 1:5.
I hope that someone has an answer to my problem and understand what I'm having trouble with.
Thanks
Mestika
Hey guys, I have a program that allows me to run queries against a large database.
I have two tables that are important right now, Deposits and withdraws. Each contains a history of every user. I need to take each table, add up every deposit and withdraws (per user), then subtract the withdraws from the deposits. I then need to return every user whos result is negative (aka they withdrew more then they deposited).
Is this possible in one query?
Example:
Deposit Table:
|ID|UserName|Amount|
|1 | Use1 |100.00|
|2 | Use1 |50.00 |
|3 | Use2 |25.00 |
|4 | Use1 | 5.00 |
WithDraw Table:
|ID|UserName|Amount|
|2 | Use2 | 5.00 |
|1 | Use1 |100.00|
|4 | Use1 | 5.00 |
|3 | Use2 |25.00 |
So then the result would output:
|OverWithdrawers|
| Use2 |
Is this possible (I sure don't know how to do it)?
Thanks for any help,
Max
I wrote the following query, I think it's correct but I have a "missing operator" error.
SELECT * FROM results,Types WHERE results.a=Types.b
INTERSECT SELECT * FROM results,Types WHERE results.c=Types.b
Could somebody help me please?
Thanks a lot.
I have a course search engine and when I try to do a search, it takes too long to show search results. You can try to do a search here
http://76.12.87.164/cpd/testperformance.cfm
At that page you can also see the database tables and indexes, if any.
I'm not using Stored Procedures - the queries are inline using Coldfusion.
I think I need to create some indexes but I'm not sure what kind (clustered, non-clustered) and on what columns.
Thanks