i have a table with 6 fields. the columns are ID, new_id price,title,Img,Active. I have datawhich is duplicated for the price column.
When I do a select i want to show only distinct rows where new_id is not the same.
e.g.-
ID New_ID Price Title Img Active
1 1 20.00 PA-1 0X4... 1
2 1 10.00 PA-10 0X4... 1
3 3 20.00 PA-11 0X4... 1
4 4 30.00 PA-5 0X4... 1
5 9 20.00 PA-99A 0X4... 1
6 3 50.00 PA-55 0X4... 1
When the select statement runs, only rows with ID (1,4,9,6) should show. Reason being the new_ID with the higher price should show up.
How can i do this?
Hi All,
Am having columns as category and songs in my table for each category there are almost 10 songs and in total there are 7 category such that which was tabled as
category1 songCategory1a
category1 songCategory1b
category1 songCategory1c
---
category2 songCategory2a
category2 songCategory2b
category2 songCategory2c
---
category3 songCategory3a
category3 songCategory3b
category3 songCategory3c
---
like that there is table in that i want to get the result as
category1
category2
category3
category4
kindly any one help me ,
i tried
(from s in _context.db_songs
select new { s.Song_Name, s.Song_Category }).Distinct().ToList(); but it didnt work its resulting as such.
Hello!
In my database, I have a "users", a "quests" and a "questings" table.
A user can solve a quest. Solving a quest will save the "user_id" and the "quest_id" in my "questings" table.
Now, I want to select all quests, a user has NOT solved (meaning there is no entry for this user and quest in "questings" table)!
Let's say the user has the id 14. How to write this query?
After solving this query, I want to filter the results, too.
A quest and a user has a city, too.
What to do for writing a query which returns all quests, a user has NOT solved yet, in the users city (user city == quest city)?
I have a temporary table that I'm using and I have a unique column, example:myID INT UNIQUE
Would this create an index on that column? Or do I have to explicitly create the index?
If I want to get a user that has the email address of '[email protected]', how do I pass that as a parameter in linq?
ie.:
var a = from u in Users
where u.Email = @email
Select u;
So this would be used in my method:
public static GetuserByEmail(string email)
Do I just pass in the variable or?
I'm trying to rename the columns. The syntax should be the column name between double quotes incase of two words, like this:
SELECT p_Name "Product Name" from items
So I'm trying to do it in C# code like this:
string sqlqry1 = "SELECT p_Name \"Prodcut Name\" from items";
But I get an error:
Syntax error (missing operator) in query expression 'p_Name "Prodcut Name"'.
It seems am having somthing wrong with the quotes, but I can't figure out.
I have a report that we need to link (which we've checked to be working) to in a JSF project, the link looks like the following:
http://www.example.com/report/summary&rs:Command=Render
However when we try to load the page that links to it we get the following error:
The reference to entity "rs:Command" must end with the ';'
How can I link to the report within my pages and prevent it from trying to parse the rs:Command?
I am trying to convert VBA code to vb.net, im having trouble trying to search the database for a specific value around an if statement. any suggestions would be greatly appriciated.
thedatabase is called confirmation, type is the column and email is the value im looking for. could datasets work?
Function SendEmails() As Boolean
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim intResponse As Integer
Dim confirmation As New ADODB.Recordset
Dim details As New ADODB.Recordset
On Error GoTo Err_Execute
Dim MyConnObj As New ADODB.Connection
Dim cn As New ADODB.Connection()
MyConnObj.Open( _
"Provider = sqloledb;" & _
"Server=myserver;" & _
"Database=Email_Text;" & _
"User Id=bla;" & _
"Password=bla;")
confirmation.Open("Confirmation_list", MyConnObj)
details.Open("MessagesToSend", MyConnObj)
If details.EOF = False Then
confirmation.MoveFirst()
Do While Not confirmation.EOF
If confirmation![Type] = "Email" Then
' Create the Outlook session.
objOutlook = CreateObject("Outlook.Application")
' Create the message.
End IF
SELECT EmployeeMaster.EmpNo, Sum(LeaveApplications.LeaveDaysTaken) AS LeaveDays
FROM EmployeeMaster FULL OUTER JOIN
LeaveApplications ON EmployeeMaster.id = LeaveApplications.EmployeeRecordID INNER JOIN
LeaveMaster ON EmployeeMaster.id = LeaveMaster.EmpRecordID
GRoup BY EmployeeMaster.EmpNo
order by LeaveDays Desc
with the above query, if an employee has no leave application record in table LeaveApplications, then their Sum(LeaveApplications.LeaveDaysTaken) AS LeaveDays column returns NULL. What i would like to do is place a value of 0 (Zero) instead of NULL. I want to do this because i have a calculated column in the same query whose formular depends on the LeaveDays returned and when LeaveDays is NULL, the formular some how fails. Is there away i can put 0 for NULL such that that i can get my desired result.
Found this solution to get substring after slash () character
DECLARE @st1 varchar(10)
SET @st1 = 'MYTEST\aftercompare'
SELECT @st1
,SUBSTRING(@st1, CHARINDEX('\', @st1) + 1, LEN(@st1))
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/5c3a5e2c-54fc-43dd-b12c-1a1f6784d7d8/tsql-get-substring-after-slash-character
But is there a way to get substring after second slash or even more?
DECLARE @st1 varchar(50)
--Added more slashes
SET @st1 = 'MYTEST\aftercompare\slash2\slash3\slash4'
SELECT @st1
--This part would need some work
--,SUBSTRING(@st1, CHARINDEX('\', @st1) + 1, LEN(@st1))
And getting only the substring between the slashes.
Values: [1] "aftercompare" - [2] "slash2" - [3] "slash3" - [4] "slash4"
I have a table that has millions of records and we are looking at implementing table partitioning. Looking at it we have a foreign key "GroupID" that we would like to partition on. Is this possible?
The Group will have more entries added to it, so as new GroupID's are added can the partition's be made dynamically?
I currently have the following code to generate a sales report over the last 30 days. I'd like to know if it would be possible to use linq to generate this report in one step instead of the rather basic loop I have here.
For my requirement, every day needs to return a value to me so if there are no sales for any day then a 0 is returned.
Any of the Sum linq examples out there don't explain how it would be possible to include a where filter so I am confused on how to get the total amount per day, or a 0 if no sales, for the last days I pass through.
Thanks for your help,
Rich
//setup date ranges to use
DateTime startDate = DateTime.Now.AddDays(-29);
DateTime endDate = DateTime.Now.AddDays(1);
TimeSpan startTS = new TimeSpan(0, 0, 0);
TimeSpan endTS = new TimeSpan(23, 59, 59);
using (var dc = new DataContext())
{
//get database sales from 29 days ago at midnight to the end of today
var salesForDay = dc.Orders.Where(b => b.OrderDateTime > Convert.ToDateTime(startDate.Date + startTS) && b.OrderDateTime <= Convert.ToDateTime(endDate.Date + endTS));
//loop through each day and sum up the total orders, if none then set to 0
while (startDate != endDate)
{
decimal totalSales = 0m;
DateTime startDay = startDate.Date + startTS;
DateTime endDay = startDate.Date + endTS;
foreach (var sale in salesForDay.Where(b => b.OrderDateTime > startDay && b.OrderDateTime <= endDay))
{
totalSales += (decimal)sale.OrderPrice;
}
Response.Write("From Date: " + startDay + " - To Date: " + endDay + ". Sales: " + String.Format("{0:0.00}", totalSales) + "<br>");
//move to next day
startDate = startDate.AddDays(1);
}
}
HI,
Currently i have one big datacontex with 35 tables (i dragged all my DB tables to the designer). I must admit it is very comfortable cause i have ORM to my full DB and query with linq is easy and simple.
My questions are:
1. Would you consider it bad design to have one datacontext with 35 tables or should i split it to logic units?
2. Is there any performance penalties for using such a big datacontext?
Thanks, Pini.
What is the most effective and flexible way to generate combinations in TSQL?
With 'Flexible', I mean you should be able to add easily combination rules. e.g.: to generate combinatories of 'n' elements, sorting, remove duplicates, get combinatories where each prize belongs to a different lottery, etc.
For example, Having a set of numbers representing lottery prizes.
Number | Position | Lottery
---------------------------
12 | 01 | 67
12 | 02 | 67
34 | 03 | 67
43 | 01 | 89
72 | 02 | 89
33 | 03 | 89
(I include the position column because, a number could be repeated among different lottery's prizes)
I would like to generate combinatories like:
Numbers | Lotteries
-------------------
12 12 | 67 67
12 34 | 67 67
12 34 | 67 67
12 43 | 67 89
12 72 | 67 89
12 33 | 67 89
.
.
.
I use GET to get the id of a result.
$id = $_GET['id'];
I then use the following code:
<?
$q = $database->friendlyDetails($id);
while( $row=mysql_fetch_assoc($q) )
{
$hu = $row['home_user'];
$ht = $row['home_team'];
$hs = $row['home_score'];
$au = $row['away_user'];
$at = $row['away_team'];
$as = $row['away_score'];
$game = $row['game'];
$name = $row['name'];
$match = $row['match_report1'];
$compid = $row['compid'];
$date = $row['date_submitted'];
$sub = $row['user_submitted'];
}
?>
And friendDetails-
function friendlyDetails($i)
{
$q = "SELECT *
FROM ".TBL_SUB_RESULTS."
INNER JOIN ".TBL_FRIENDLY."
ON ".TBL_FRIENDLY.".id = ".TBL_SUB_RESULTS.".compid
WHERE ".TBL_SUB_RESULTS.".id = '$i'";
return mysql_query($q, $this->connection);
}
For some reason, the code will only return what is under id =1.
Can anyone see anything obvious I am doing wrong?
I've got two database servers,
(1) production
(2) test
on the production database I get frequent deadlocks and I'm trying to find out what is causing it.
I take a backup of the database in production and restore it in test and when I perform the exact same scenario that yields deadlocks on the production server I am unable to reproduce in test.
any ideas/tips/hints would be much appreciated.
I have 3 tables,
- Section table that defines some general item sections.
- Category table - has a "section" column (foreign key).
- Product table - has a "category" column (foreign key).
I want to get all products that belong to X section.
How can I do it?
select from select?
Is there any way to set one job priority higher then other,
In my case there are two jobs those are working on same set of tables,first JOB-A which is running every 12 hr and other JOB-B is every 10 minutes , i think at some time when they run simultaneously JOB-B is getting in to deadlock and get failed,
i google the topic and found sqlgoverner is helpful in such cases
does anyone know how to resolve?
I have an web application that creates printable forms, these forms have a unique number on them, the problem is I have 2 forms that separate numbers need to be created for them.
ie)
Form1- Numbered 2000000-2999999
Form2- Numbered 3000000-3999999
dbo.test2 - is my form information table
Tsel - is my autoinc table for the 3000000 series numbers
Tadv - is my autoinc table for the 2000000 series numbers
What I have done is create 2 tables with just autoinc row (one for 2000000 series numbers and one for 3000000 series numbers), I then created a trigger to add a record to the coresponding table, read back the autoinc number and add it to my table that stores the form information including the just created autoinc number for the right series of forms.
Although it does work, I'm concerned that the numbers will get messed up under load.
I'm not sure the @@IDENTITY will always return the right value when many people are using the system. (I cannot have duplicates and I need to use the numbering form show above.
See code below.
** TRIGGER **
CREATE TRIGGER MAKEANID2 ON dbo.test2
AFTER INSERT
AS
SET NOCOUNT ON
declare @someid int
declare @someid2 int
declare @startfrom int
declare @test1 varchar(10)
select @someid=@@IDENTITY
select @test1 = (Select name1 from test2 where sysid = @someid )
if @test1 = 'select'
begin
insert into Tsel Default values
select @someid2 = @@IDENTITY
end
if @test1 = 'adv'
begin
insert into Tadv Default values
select @someid2 = @@IDENTITY
end
update test2
set name2=(@someid2) where sysid = @someid
SET NOCOUNT OFF
If i have a table with two fields.customer id and order.
let's say i have in total order ID 1,2,3,4
all the customer can have all the four orders.like below
1234 1
1234 2
1234 3
1234 4
3245 3
3245 4
5436 2
5436 4
you can see above that 3245 customer doesnt have order id 1 and 2.
how could i print in the query output like
3245 1
3245 2
5436 1
5436 3
EDIT: i dont have order table but i have list of order's like we can hard code it in the query(1,2,3,4) i dont have an orders table.
I have a bunch of records I want to move to another database and I just want to create a bunch of inserts that I can copy and paste. I've seen someone do this before but I can't figure it out. I'm not getting the escapes right.
It's something like this where 'Code', 'Description' and 'Absent' are the columns I want from the table.
SELECT 'INSERT INTO AttendanceCodes
(Code, Description, Absent)
VALUES
(' + Code + ',' + Description + ',' + Absent')'
FROM AttendanceCodes
The end result should be a slew of INSERTS with the correct values like this:
INSERT INTO AttendanceCodes
(Code, Description, Absent)
VALUES
('A','Unverified Absence','UA')
I am adding a new GUID/Uniqueidentifier column to my table.
ALTER TABLE table_name
ADD VersionNumber UNIQUEIDENTIFIER UNIQUE NOT NULL DEFAULT NEWSEQUENTIALID()
GO
And when ever a record is updated in the table, I would want to update this column "VersionNumber". So I create a new trigger
CREATE TRIGGER [DBO].[TR_TABLE_NAMWE]
ON [DBO].[TABLE_NAME]
AFTER UPDATE
AS
BEGIN
UPDATE TABLE_NAME
SET VERSIONNUMBER=NEWSEQUENTIALID()
FROM TABLE_NAME D
JOIN INSERTED I ON D.ID=I.ID/* some ID which is used to join*/
END
GO
But just realized that NEWSEQUENTIALID() can only be used with CREATE TABLE or ALTER TABLE. I got this error
The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type 'uniqueidentifier' in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression.
Is there a workaround for this ?
Edit1: Changing NEWSEQUENTIALID() to NEWID() in the trigger solves this, but I am indexing this column and using NEWID() would be sub-optimal
Hello, I have MSSQL 2008 Ent and OLTP database with two big tables. How I can move this tables to another filegroup without service interrupting? Now, about 100-130 records inserted and 30-50 records updated each second in this tables. Each table have about 100M records and six fields (including one field geography).
I looking for solution via google, but all solutions contain "create second table, insert rows from first table, drop first table, bla bla bla".
Can I use partitioning functions for solving this problem? Thank you.