SQL syntax using C# - c#

I'm trying to insert values into some table with this code using C# and SQL:
string query1 = "select PlayerID from Table1";
string query2 = "select GameID from Table2";
string q = "insert into Table3 (PlayerID, GameID) values(" + query1 + "," + query2 + ")";
Is it possible?
Edit:
I have 3 tables:
playersTbl - with auto increment id (primary key)
gameTbl - with auto increment id (primary key)
JoinTbl
When the game is starting, the user can register some players to the same game, so
in the same game lets say there are 4 players.
When I'm adding those 4 players the playersTbl will look like:
ID | first name|
----------------
1 | p1 |
2 | p2 |
3 | p3 |
4 | p4 |
and the gameTbl will look like:
ID | Date | Hour|
-----------------
1 | | |
So what I'm trying to do is the Table3 will look like:
PlayerID | GameID|
------------------
1 | 1 |
2 | 1 |
3 | 1 |
4 | 1 |
Now when I'm starting a new game with one player
I'm adding the player to the playersTbl, and the game to the gameTbl, but now the third table will look like
PlayerID | GameID|
------------------
1 | 1 |
2 | 1 |
3 | 1 |
4 | 1 |
5 | 2 |
to be more clear, I don't want that players which are registered in the second game will be in the first game..

use INSERT INTO..SELECT statement,
INSERT INTO Table3(PlayerID, GameID)
SELECT a.PlayerID, b.GameID
FROM Table1 a CROSS JOIN Table2 b
what the query does is it produces cartesian product from both tables.
Consider The following example,
Table1
PlayerID
========
1
2
3
Table2
GameID
=======
10
11
12
when the query below is executed,
SELECT a.PlayerID, b.GameID
FROM Table1 a CROSS JOIN Table2 b
it produces the following result,
PlayerID GameID
========= ======
1 10
1 11
1 12
2 10
2 11
2 12
3 10
3 11
3 12

You should be able to utilize the INSERT INTO SELECT method, like this:
INSERT INTO Table3 (PlayerID, GameID) SELECT Table1.ID, Table2.ID FROM Table1, Table2

Related

Create a stored procedure to display rows with a connected column value from another column

I have this SQL Server database already stored
ID | TaxDecNo | OwnerName | PrevTaxDec
----------------------------------------------
1 | 5374 | John | 11135
2 | 9864 | Doe | 7394
3 | 11135 | John | 21784
4 | 7394 | Doe | 6872
5 | 21784 | John | NULL
6 | 6872 | Doe | NULL
When I'm going to display ID 3
ID | TaxDecNo | OwnerName | PrevTaxDec
----------------------------------------------
1 | 5374 | John | 11135
3 | 11135 | John | 21784
5 | 21784 | John | NULL
When I'm going to display RecordID 2
ID | TaxDecNo | OwnerName | PrevTaxDec
----------------------------------------------
2 | 9864 | Doe | 7394
4 | 7394 | Doe | 6872
6 | 6872 | Doe | NULL
The display only stop when no PrevTaxDec connects TaxDec No value.
I got this solution given to me a while but I don't know how to convert it to stored procedure which the data is already inserted the table
DECLARE #ID int = 3;
WITH YourTable AS(
SELECT V.ID,
V.TaxDecNo,
V.PrevTaxDec
FROM (VALUES(1,5374,11135), --This value must already inserted in the table
(2,9864,7394),
(3,11135,21784),
(4,7394,6872),
(5,21784,NULL), --I assume you aren't really mixing datatyoes. 'N/A' can't be inserted into an int column
(6,6872,NULL))V(ID,TaxDecNo,PrevTaxDec)),
--Solution
rCTEup AS(
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM YourTable YT
WHERE YT.ID = #ID
UNION ALL
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM rCTEup r
JOIN YourTable YT ON r.TaxDecNo = YT.PrevTaxDec),
rCTEdown AS(
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM YourTable YT
WHERE YT.ID = #ID
UNION ALL
SELECT YT.ID,
YT.TaxDecNo,
YT.PrevTaxDec
FROM rCTEdown r
JOIN YourTable YT ON r.PrevTaxDec = YT.TaxDecNo)
SELECT ID,
TaxDecNo,
PrevTaxDec
FROM rCTEup
UNION ALL
SELECT ID,
TaxDecNo,
PrevTaxDec
FROM rCTEdown
WHERE ID != #ID; --As it'll be in rCTEup

Select values from one table based on specific value of another table Linq

I have 2 tables:
Location
id | user_id | latitude | longitude|
1 | 2 | 11.32323 | 11.32323 |
2 | 3 | 12.32323 | 12.32323 |
3 | 4 | 21.32323 | 12.32323 |
Task
id | user_id | status |
1 | 2 | 0 |
2 | 2 | 1 |
3 | 2 | 0 |
4 | 2 | 2 |
5 | 2 | 1 |
6 | 2 | 0 |
7 | 3 | 1 |
8 | 3 | 1 |
9 | 3 | 1 |
I want to select all rows from location table in which users have
either no record in Tasks table (for e.g. user_id = 4)
or if records
exists then all of them must have status equals to 1 (for e.g. user_id
= 3).
In above example, user_id = 2 should not be selected because it has rows in Tasks table with status other than 1.
I am not very much familiar with SQL and LINQ so any help would be appreciated.
This is the expected result:
Result
id | user_id | latitude | longitude|
2 | 3 | 12.32323 | 12.32323 |
3 | 4 | 21.32323 | 12.32323 |
Location with user_id = 2 was ignored because it has some rows in Tasks table with status other than 1.
Location with user_id = 3 was selected because all rows in Tasks table has status = 1.
Location with user_id = 4 was selected because there were no rows in Tasks table with user_id = 4.
Looking at you requirements could be this
select * from location
where user_id not in (select distinct user_id from task )
or user_id not in (select distinct user_id from task where status != 1);
Your conditions are equivalent to saying that no non-"1" value exists in task. I would write this as:
select l.*
from location l
where not exists (select 1 from tasks where t.user_id = l.user_id and t.status = 1);
I prefer not exists to not in because not in will filter out all rows if user_id is ever NULL in tasks.
Using a LEFT JOIN without a sub-SELECT:
SELECT
l.id,
l.user_id,
l.latitude,
l.longitude
FROM
Location l
LEFT JOIN Task t
ON l.user_id = t.user_id
WHERE
t.id IS NULL /* No record in tasks table */
OR (t.id IS NOT NULL AND l.status = 1) /* if records exists then all of them must have status equals to 1 */

LINQ join tables with value if no match

I know that there are some examples but I could not apply them on my code. I am pretty new to Linq and SQL. I have two tables I want to join.
First Table:
--------------
| Id | Count |
--------------
| 1 | 10 |
--------------
| 2 | 4 |
--------------
Second Table:
--------------
| Id | Name |
--------------
| 1 | Tom |
--------------
| 2 | John |
--------------
| 3 | Nick |
--------------
| 4 | Max |
--------------
As you can see, the second table has more records than the first. My goal is to join them based on the Id. The problem is that after I have joined the tables it only displays the matching records, which is Id 1 and 2. Though I want to display every Id (from 1 to 4) and if there is no match in both tables, there should be a default value 0.
It should look like this:
----------------------
| Id | Name | Count |
----------------------
| 1 | Tom | 10 |
----------------------
| 2 | John | 4 |
----------------------
| 3 | Nick | 0 |
----------------------
| 4 | Max | 0 |
----------------------
So far I have got this code:
// first table
var listCount = entity.tblKundes.Where(x => x.Studio == 2)
.Select(x => new { x.Id, x.Name})
.GroupBy(x => x.Name).ToList();
// second table
var listBerater = entity.tblUsers.Where(x => x.Studio == 2)
.Select(x => new { x.Id, x.Name})
.ToList();
// This join should be edited so that it displays non matching records as well
var test = listCount.Join(
listBerater,
count => count.Key,
berater => berater.Id,
(count, berater) => new { listCount = count, listBerater = berater }
).ToList();
Edit:
var test2 = (from list in listCount
join berater in listBerater on list.Berater equals berater.Id into gj
from sublist in gj.DefaultIfEmpty()
select new { sublist.Id, sublist.Nachname, sublist.Vorname }).ToList();
There is a typical concept in every Structured Query Languages which is called "Left join". Left-Join means that you will have all rows of data from first table even there is no equivalent in the second one. "Inner-Join" is a little different and only looks for matched rows of data.
Here you can find enough and complete information about your issue.
Left Join

Linq Left Outer Join With newest datetime in right side

I have "Orders" table where its primary key is "OrderId ":
OrderId | OrderName
------- | ----------
1 | Order X
2 | Order Y
3 | Order Z
and "OrderDetails" table where its primary key is "OrderDetailsId " foreign key is 'OrderId":
OrderDetailsId | OrderId | ItemId | DeliveryDate
-------------- | ------- | ------ | ------------
10 | 1 | AA | 1/1/2010
20 | 1 | BB | 1/1/2013
30 | 2 | CC | 1/1/2012
40 | 2 | CC | 1/1/2014
Each order has ZERO or more order details, each order detail has specific delivery date.
We want to get all the orders, whether they have order details or not, and mark just one order as VIP if it has the order detail that has the maximum "delivery date"
This is the expected output:
OrderId | OrderName | IsVIP
------- | --------- | -----
1 | Order X | NO
2 | Order Y | YES
3 | Order Z | NO (since it has no order details)
That's because the maximum delivery date is for OrderDetailsId = 40 which belongs to OrderId = 2
How to accomplish this using the most readable LINQ code
I am not sure if you have OrderDetails property in orders collection (if so then #juharr's answer is correct). But, if they are not then you can make use of group join like this:-
var result = from o in orders
join od in orderDetails
on o.OrderId equals od.OrderId into g
select new {
OrderId = o.OrderId,
OrderName = o.OrderName,
IsVIP = g.Any(x => x.DeliveryDate == orderDetails.Max(z => z.DeliveryDate))
? "Yes" : "No"
};
Here is an example Fiddle with linq-to-objects.
Use navigation properties. Note this will set IsVIP to "YES" for all orders that contain an order detail with the max delivery date.
var query = from order in db.Orders
select new
{
order.OrderId,
order.Name,
IsVIP = order.OrderDetails.Any(
od => od.DeliveryDate == db.OrderDetails.Max(x => x.DeliveryDate))
? "YES"
: "NO"
};

Grouping relational data into a single Datatable

I'm developing a system using WinForms C#.
I have two relational tables:
USER_PROFILE
| ID | NAME |
1 prof1
PERMISSIONS
| UPROFILE_ID | PERMISSION |
1 abc
1 acb
1 bca
I need to show the profiles on screen.
I dont know if it's the best fitting solution for my case, or how to implement it. My idea is to display in a DataGridView like this:
| Profile | Permission1 | Permission2 | Permission3 |
prof1 abc acb bca
Any suggestions?
Thanks in advance.
You can use 'case switch' to convert row into column. In actual select query you can construct column list dynamically.
Example:-
SQL> select id,name from user_profile;
ID NAME
1 U1
2 U2
SQL> select id,pname from per order by 1;
ID PNAME
1 A
1 B
2 C
SQL> select distinct u.name user_name, case when p.pname='A'then p.pname else null end permission1, case when p.pname='B' then p.pname else null end permission2 from user_profile u, per p where u.id=p.id order by 1;
USER_NAME PERMISSION1 PERMISSION2
-------------------- -------------------- --------------------
U1 A
U1 B
U2

Categories