Fetch data from a database from two different tables - c#

I am using C#(asp.net). I have two tables(data and details) in a same database.
Table "data"
id | chap | unit |
----------------
1| chap1|unit1 |
2| chap2|unit2 |
3| chap3|unit3 |
Table "details"
id| code| num |
----------------
1|abc |2 |
2|efg |3 |
3|hij |1 |
Now I want to fetch a value from "num" where code="efg" (in table "details"). And use the same value (3) to fetch data from table "data" by id. I am using this code.
OleDbConnection conn = new OleDbConnection(*** ...... *****);
OleDbCommand cmd;
OleDbDataReader reader;
String query = String.Format("select num from details where code="efg");
cmd = new OleDbCommand(query, conn);
reader = cmd.ExecuteReader();
int num = int.Parse(reader.GetValue(0).ToString());
query = String.Format("select chap from data where id={0}",num);
cmd = new OleDbCommand("select lesson from data where id=3", conn);
reader = cmd.ExecuteReader();
Label1.Text = reader.GetValue(0).ToString();
But it shows error. It shows "No data exists for the row/column."

You can use
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
WHERE de.code = 'efg'
or
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
AND de.code = 'efg'
More: if you're using SQL-Server, use SqlConnection in place of OleDbConnection.
More: don't format your query joining strings, numbers, dates and so on; use SqlParameter so you don't have to worry about types and formatting!!

Or you can use a subquery
SELECT * FROM data INNER JOIN
(SELECT num FROM details WHERE code='efg') det
ON data.id = det.num

Related

How do I get the values from Npgsql if I use Select with multiple columns

If for example I have this query:
SELECT (column1, column2, column3) FROM table
And I ran ExecuteReader().
If column1 and column3 are strings and column 2 is an Id which are integers.
How do I get the values from each column? I tried it with the normal Get functions from the Reader, I would always get a Cast Exception Error can't cast database type to string/int
/ Edit
This is my test code:
conn1.Open();
string sql_reader = "SELECT (id, employee_number, first_name, last_name) FROM employee";
using var cmd_reader = new NpgsqlCommand(sql_reader, conn1);
var reader = cmd_reader.ExecuteReader();
while (reader.Read())
{
System.Diagnostics.Debug.WriteLine(reader.GetFieldValue<int>(0));
}
conn1.Close();
I would get a "System.InvalidCastException" if I ran this code.
And if I would change reader.GetFieldValue<int>(0) to reader.GetFieldValue<string>(1) I would get an out of range error "column must be between 0 and 0".
Remove the parentheses.
In all other databases they are useless noise, but in Postgres the expression (column1, column2, column3) creates an anonymous record - so your result contains only a single column (which is that anonymous record that contains three fields).
e.g. this sample data:
create table t1 (c1 int, c2 int, c3 int);
insert into t1 values (1,2,3);
Then this query:
select (c1, c2, c3) as rec
from t1;
returns:
rec
-------
(1,2,3)
But this
select c1, c2, c3
from t1;
returns the expected result
c1 | c2 | c3
---+----+---
1 | 2 | 3
Online example
Specifically, in your case, each line will consist of an array of objects with a length equal to 4.
conn1.Open();
string sql_reader = "SELECT (id, employee_number, first_name, last_name) FROM employee";
using var cmd_reader = new NpgsqlCommand(sql_reader, conn1);
using var reader = cmd_reader.ExecuteReader();
while (reader.Read())
{
var value = reader.GetFieldValue<object[]>(0);//value.Length is 4
//I assumed that "id" and "employee_number" are int in your table.
//value[0] is id
//value[1] is employee_number
//...
}
conn1.Close();
Starting with Npgsql 6.0:
conn1.Open();
string sql_reader = "SELECT (id, employee_number, first_name, last_name) FROM employee";
using var cmd_reader = new NpgsqlCommand(sql_reader, conn1);
using var reader = cmd_reader.ExecuteReader();
while (reader.Read())
{
using var internalReader = reader.GetData(0);//row reader
while(internalReader.Read())
{
var id = internalReader.GetFieldValue<int>(0);
var employee_number = internalReader.GetFieldValue<int>(1);
var first_name = internalReader.GetFieldValue<string>(2);
var last_name = internalReader.GetFieldValue<string>(3);
}
}
conn1.Close();

Replace values from Select query in SQL using C#

My SQL query is:
GridView1.DataSource = GetData();
GridView1.DataBind();
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["OfficeConnection"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Consulting ", con))
{
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
}
}
return dt;
}
I have a table with a few columns and what I am trying to achieve is to display the data in a GridView. At the moment the data is displayed in my GridView but I would like to replace text in the columns and then display in the gridview
So for example this is my table:
| DisplayName | $_License
+-------------+------------------------
| User 1 | TestLicense:License1 |
| User 2 | TestLicense:License2 |
So in my Gridview I would to display:
| Display Name | License Type |
+--------------+------------------------+
| User 1 | License1 |
| User 2 | License2 |
Note that theDisplay Name has a space and the $_License is changed to License Type and the row is changed from TestLicense:License1 to License1
Any help will be greatly appreciated.
Use this query:
"SELECT DisplayName 'Display Name', Replace($_License,'TestLicense:', '') 'License Type' Name FROM Consulting "
Modify your select query as per required result:
SELECT DisplayName AS 'Display Name' , RIGHT($_License, LEN($_License) - 11) AS 'License Type' FROM Consulting;

some selected fields as Pivote column ASP.NET

I want to show some selected columns as my SQL column and the rest of the column should be pivot. My output should be: Please help me any idea ?
Pivot table
ID | Employee_ID | 01-sep-2019 | 02-sep-2019 | 03-sep-2019
───┼─────────────┼─────────────┼─────────────┼────────────
1 | 1001 | P | A | P
2 | 1002 | A | P | A
3 | 1003 | A | P | P
Original table
ID | Employee_ID |STATUS | Created_Date
───┼─────────────┼───────┼─────────────
1 | 1001 | P | 01-sep-2019
2 | 1002 | A | 02-sep-2019
3 | 1003 | P | 03-sep-2019
I use 2 `GridView to show data but it's applicable for all column that I don't need. Could you please help me?
private DataTable PivotTable(DataTable origTable) {
DataTable newTable = new DataTable();
DataRow dr = null;
//Add Columns to new Table
for (int i = 0; i <= origTable.Rows.Count; i++) {
newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
}
//Execute the Pivot Method
for (int cols = 0; cols < origTable.Columns.Count; cols++) {
dr = newTable.NewRow();
for (int rows = 0; rows < origTable.Rows.Count; rows++) {
if (rows < origTable.Columns.Count) {
dr[0] = origTable.Columns[cols].ColumnName; // Add the Column Name in the first Column
dr[rows + 1] = origTable.Rows[rows][cols];
}
}
newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
}
return newTable;
}
private void BindGridView() {
string strConnString = ConfigurationManager.ConnectionStrings["SQLDBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
try {
con.Open();
string sqlStatement = "SELECT Top(5)* FROM tbl_QC_Attandence";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt.Rows.Count > 0) {
//Bind the First GridView with the original data from the DataTable
grdorignal.DataSource = dt;
grdorignal.DataBind();
//Pivot the Original data from the DataTable by calling the
//method PivotTable and pass the dt as the parameter
DataTable pivotedTable = PivotTable(dt);
grdpivote.DataSource = pivotedTable;
grdpivote.DataBind();
}
} catch (System.Data.SqlClient.SqlException ex) {
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
} finally {
con.Close();
}
}
ORIGINAL TABLE
ID Employee_ID STATUS Created_Date
1 1001 P 01-sep-2019
2 1002 A 02-sep-2019
3 1003 P 03-sep-2019
PIVOT TABLE
ID Employee_ID 01-sep-2019 02-sep-2019 03-sep-2019
1 1001 P A P
2 1002 A P A
3 1003 A P P
I have create a dynamic query which can help you, but null can be replaced with 'A' in code side, try below one
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '',
#SelectColumnNames AS NVARCHAR(MAX);
SELECT
#columns += QUOTENAME([Created_Date]) + ','
FROM
Employee
ORDER BY
[Created_Date];
SET #columns = LEFT(#columns, LEN(#columns) - 1);
Select #SelectColumnNames = ISNULL(#SelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME([STATUS]) + ', 0) AS '
+ QUOTENAME([STATUS])
from (SELECT distinct [STATUS] from Employee) as Employees
print #SelectColumnNames
SET #sql =
N'Select * from(
select Created_Date,[STATUS],ID,Employee_ID
from Employee
)t
PIVOT(
MAX([STATUS])
FOR [Created_Date] IN ('+ #columns +')
) AS pivot_table
';
EXECUTE sp_executesql #sql;

Updating rows on a table with condition

I'm trying to delete all the rows, starting from the bottom of the table using a condition, but when that conditions is met then i want it to stop updating the table and leave the rest as it was. Example, if the last entry on the table meets it, delete it, if the one after it does not meet the condition then stop there, and exite the loop.
Here's the code i got, but its deleting all the rows :
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("A atualizar dados");
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab
WHERE serie ='1' AND tipodoc ='FSS'
AND contribuinte ='999999990'
and datadoc = CONVERT(varchar(10),(dateadd(dd, -2, getdate())),120)"
SqlCommand command = new SqlCommand(queryString, connection);
//command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * FROM wgcdoccab
WHERE serie !='1' and tipodoc !='FSS'
and contribuinte !='999999990'
and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120) ";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
MessageBox.Show("Dados Apagados com sucesso");
}
command.Connection.Close();
}
}
}
while (check);
Try something like this example:
DELETE
FROM tableName
WHERE ID >
(
SELECT MAX(ID)
FROM tableName
WHERE condition = false
)
For example, if you want to delete until a value is 4:
DELETE
FROM tableName
WHERE ID >
(
SELECT MAX(ID)
FROM tableName
WHERE tableName.Value = 4
)
If the table rows are:
|ID|Value|
| 1| 7|
| 2| 4|
Then the subselect will be 2 and no rows will be deleted. However, if the rows are:
|ID|Value|
| 1| 7|
| 2| 4|
| 3| 9|
| 4| 1|
Then the subselect will still return the ID of 2, and the last 2 rows will be deleted.

how to read last data of column using datareader in asp.net c#

I have one database and I want to get last value of column, and each time value will be updated after insertion
here is sample database,
ID | Customer_Name |new_Total | Total
--------------------------------------
1 | Mahesh | 100 | 200
2 | Mahesh | 400 | 600 (200+400)
3 | mahesh | 100 | 700 (600+100)
If i am getting you right you need to get last value of column i assume Total column.Here is you can read last value from database.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
{
SqlCommand cmd = new SqlCommand("select Top 1 Total from tablename order by total desc", con);
SqlDataReader rdr;
con.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int total;
int.TryParse(rdr["Total"].ToString(), out total);
}
}
You will get value in total variable and you can use it.

Categories