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?
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
I have recently started using custom ViewModels (For example, CustomerViewModel)
public class CustomerViewModel
{
public IList<Customer> Customers{ get; set; }
public int ProductId{ get; set; }
public CustomerViewModel(IList<Customer> customers, int productId)
{
this.Customers= customers;
this.ProductId= productId;
}
public CustomerViewModel()
{
}
}
... and am now passing them to my view instead of the Entities themselves (for example, var Custs = repository.getAllCusts(id) ) as it seems good practice to do so.
The problem i have encountered is that when using ViewModels; by the time it has got to the the view i have lost the ability to lazy load on customers. I do not believe this was the case before using them.
Is it possible to retain the ability of Lazy Loading while still using ViewModels?
Or do i have to eager load using this method?
Thanks,
Kohan.
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!
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;
}
After performing a database restore, I want to run a dynamic script to fix ophaned users. My script below loops through all users that are displayed after executing sp_change_users_login 'report' and apply "alter user [username] with login = [username]" to fix SID conflicts verses static go statements. Although, I'm getting an "incorrect syntax error on line 15." can't figure out why...
DECLARE @Username varchar(100), @cmd varchar(100)
DECLARE userLogin_cursor CURSOR FAST_FORWARD
FOR
SELECT UserName = name FROM sysusers
WHERE issqluser = 1 and (sid IS NOT NULL AND sid <> 0×0)
AND suser_sname(sid) IS NULL
ORDER BY name
FOR READ ONLY
OPEN userLogin_cursor
FETCH NEXT FROM userLogin_cursor INTO @Username
WHILE @@fetch_status = 0
BEGIN
SET @cmd = ‘ALTER USER ‘+@username+‘ WITH LOGIN ‘+@username
EXECUTE(@cmd)
FETCH NEXT FROM userLogin_cursor INTO @Username
END
CLOSE userLogin_cursor
DEALLOCATE userLogin_cursor
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?
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.
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
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!
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.
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
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.
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)
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 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 some dates fields in table. These columns contain dates in the following format:
mmddyy
For example:
31/12/2010 00:00:00:0000
I need to import these values into a table which is set to varchar and numeric and formats dates like this:
monthName varchar
Year numeric(4,0)
currently I'm using
INSERT INTO [School].[dbo].[TeacherAttendenceDet]
([TeacherCode],
[MonthName],
[Year])
(SELECT MAX(employeecode),
Datename(MONTH, dateofjoining) AS MONTH,
Datepart(YEAR, dateofjoining) AS DATE
FROM employeedet
GROUP BY dateofjoining)
but datename() gives result in date format.. I have to save it in varchar format
How can I do this?
this is employeemast table:
EmployeeCode numeric(5, 0)
PayScaleCode numeric(7, 0)
DesignationCode varchar(50)
CityCode numeric(5, 0)
EmployeeName varchar(50)
FatherName varchar(50)
BirthDate varchar(50)
DateOfJoining varchar(50)
Address varchar(150)
this is TeacherAttendenceDet table
TeacherCode numeric(5, 0) Unchecked
Year numeric(4, 0) Unchecked
MonthName varchar(12) Unchecked
i have to insert in teacherattendencedet table the monthname and year from employeemast
Have a binary field and want to insert into this from a hex string:
insert into binaryTable(binaryField)
values(convert(varbinary(max), 0x0))
however when I run select the value is return with an extra 0 as 0x00
This extra 0 is causing a problem in another application, I dont want it.
Interesting, is if I do a select on an existing value and it returns say 0x55 then inserting this same value using the above query will return a select of 0x055.
How to stop the extra 0 being added?
Say I have the following tables and columns:
comp: id, model
dvd: id, model
comp2dvd: id, id_comp, id_dvd
A computer can have multiple dvd drives, even of the same model, and a dvd drive can appear in multiple computers. How do I make it so that comp2dvd table can have only existing comp and dvd ids?
Thanks
Hi All,
Could I get ideas on retrieving the dataset using lookup method. Basically, my scenario as I have source data needs to lookup for other source table and on matching column from source I need to get all the records from other source data.
its a one to many relations. I tried Lookup but gives only one record on matching condition, OLE DB command don't retrieve any data as it will do only Insert/Update operations.
Thanks
prav
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
I have the following tables:
TableA (id, tableB_id, tableC_id)
TableB (id, expirationDate)
TableC (id, expirationDate)
I want to retrieve all the results from TableA ordered by tableB.expirationDate and tableC.expirationDate. How can I do this?
This is a database design question.
I want to build an invoice web application, an invoice can have many items, and each user can have an inventory list of product items that they can store and choose to add to an invoice item.
My questions are:
1. Should I store all product inventory for all users using my application under one single table? Or have a separate product inventory table created for each user?
2. Is this even possible?
1 table is easier, but what if this single table grows too big, will I have a problem? (primary key INT).