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?
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
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
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
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.
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 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.
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)
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);
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.
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’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
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.
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?
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
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 tried to this query: What are the doctors that work on less than 2 Hospitals.
I have these tables:
CREATE TABLE Hospital (
hid INT PRIMARY KEY,
name VARCHAR(127) UNIQUE,
country VARCHAR(127),
area INT
);
CREATE TABLE Doctor (
ic INT PRIMARY KEY,
name VARCHAR(127),
date_of_birth INT,
);
CREATE TABLE Work (
hid INT,
ic INT,
since INT,
FOREIGN KEY (hid) REFERENCES Hospital (hid),
FOREIGN KEY (ic) REFERENCES Doctor (ic),
PRIMARY KEY (hid,ic)
);
I tried with this:
SELECT DISTINCT D.ic
FROM Doctor D, Work W
JOIN Hospital H ON (H.hid = W.hid)
WHERE D.bi = W.bi
GROUP BY (D.ic)
HAVING COUNT(H.hid) < 2
;
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).
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?
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
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 to make a string by using the values which the user selects on the webpage
suppose i need to display files for multiple machines with differnt search criteria..
i currently use this code:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT FileID FROM Files WHERE MachineID=@machineID and date= @date", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("@machineID", machineID);
sqlCmd.Parameters.AddWithValue("@date", date);
sqlDa.Fill(dt);
now this is fixed query where the user just has one machine and just selects one date...
i want to make a query in which the user has multiple search options like type or size if he wants depending on what he selects
also if he can select multiple machines..
SELECT FileID FROM Files WHERE (MachineID=@machineID1 or MachineID = @machineID2...) and (date= @date and size=@size and type=@type... )
all of this happens in runtime... other wise i have to create a for loop to put multiple machines one by one... and have multiple queries depending on the case the user selected...
this is quiet interesting and i could use some help...
thanks