How To Convert rows into Column in SQL? - asp.net

Actually I have query which returns me 5 columns and values(date) for each or them in a single row but what I want is the columns names should be in a single column Title and its (Vale) in second columns in Date.
Note Title and Date are the columns of the temporary table I just created run time.
Here is my piece of code I am using,
protected void btnAlerts_Click(object sender, EventArgs e)
{
fnSaveAlerts();
}
private void fnSaveAlerts()
{
DataTable dtTemp = new DataTable();
DataColumn dtC1 = new DataColumn();
dtC1.DataType = typeof(String);
dtC1.ColumnName = "Title";
DataColumn dtc2 = new DataColumn();
dtc2.DataType = typeof(DateTime);
dtC1.ColumnName = "Date";
dtTemp.Columns.Add(dtC1);
dtTemp.Columns.Add(dtc2);
LeadsContracts ObjLeadsContract = new LeadsContracts();
ObjLeadsContract.ExecuteSql(#"select dtDisclosure, dtDueDiligence,
dtFinanceAppraisals, dtFreeTextDate1,
dtFreeTextDate2
from LeadsContracts
where dtDisclosure is not null
and dtDueDiligence is not null
and dtFinanceAppraisals is not null
and dtFreeTextDate1 is not null
and dtFreeTextDate2 is not null");
dtTemp.DataSet = ObjLeadsContract.DefaultView; // it also gives error here "Red line"
}
I have already spend whole day to do this, please any body can help me. thanks in advance

I'll give you hints for a solution:
For your problem you can use a two-dimenstional array.
[0]["Title", DatabaseValue]
[1]["Date", DatabaseValue]
[2][
[3][
[4][
So, first loop over the five values of your query and fill into the two dimensional array
[0][1]
[1][1]
[2][1]
[3][1]
[4][1]
Then you can loop over the two dimensional array for your output...

Are you expecting something like this?
DECLARE #Temp AS TABLE (dtDisclosure varchar(20),dtDueDiligence varchar(20),dtFinanceAppraisals varchar(20),dtFreeTextDate1 varchar(20),dtFreeTextDate2 varchar(20))
INSERT INTO #Temp VALUES ('20-Apr-2013','20-Apr-2013','20-Apr-2013','20-Apr-2013','20-Apr-2013'),
('21-Apr-2013','21-Apr-2013','21-Apr-2013','21-Apr-2013','21-Apr-2013')
SELECT [Title],[Date] FROM
(
SELECT * FROM #temp
} A
UNPIVOT
{
[Date] FOR [Title] IN IN ([dtDisclosure],[dtDueDiligence],[dtFinanceAppraisals],[dtFreeTextDate1],[dtFreeTextDate2])
} AS Unpvt;
OUTPUT :
Title Date
dtDisclosure 20-Apr-2013
dtDueDiligence 20-Apr-2013
dtFinanceAppraisals 20-Apr-2013
dtFreeTextDate1 20-Apr-2013
dtFreeTextDate2 20-Apr-2013
dtDisclosure 21-Apr-2013
dtDueDiligence 21-Apr-2013
dtFinanceAppraisals 21-Apr-2013
dtFreeTextDate1 21-Apr-2013
dtFreeTextDate2 21-Apr-2013

Related

How do i get the Count of InventSerialId from InventDim

How do i create a query or using select to get the count of InventSerialId base on a given Itemid, InventLocationId and where the inventSum.PhysicalInvent > 0 or inventSum.Picked > 0.
This is not directly possible using X++.
Consider:
static void _TestDim(Args _args)
{
ItemId itemId = '123';
InventSum inventSum;
InventDim inventDim;
Query q = new Query();
QueryBuildDataSource ds = q.addDataSource(tableNum(InventSum), 's');
QueryRun qr;
;
// ds.addRange(fieldNum(InventSum,ItemId)).value(queryValue(itemId));
ds.addRange(fieldNum(InventSum,Closed)).value(queryValue(NoYes::No));
ds.addGroupByField(fieldNum(InventSum,ItemId));
ds.addSelectionField(fieldNum(InventSum,PhysicalInvent),SelectionField::Sum);
ds.addSelectionField(fieldNum(InventSum,Picked),SelectionField::Sum);
q.addHavingFilter(ds, fieldStr(InventSum,PhysicalInvent), AggregateFunction::Sum).value('>0');
// q.addHavingFilter(ds, fieldStr(InventSum,Picked), AggregateFunction::Sum).value('((s.Picked >0)||(s.PhysicalInvent>0))'); // This is not allowed
ds = ds.addDataSource(tableNum(InventDim), 'd');
ds.joinMode(JoinMode::InnerJoin);
ds.relations(true);
ds.addGroupByField(fieldNum(InventDim,InventSerialId));
ds.addRange(fieldNum(InventDim,InventSerialId)).value('>""');
info(q.dataSourceNo(1).toString());
qr = new QueryRun(q);
while (qr.next())
{
inventSum = qr.getNo(1);
inventDim = qr.getNo(2);
info(strFmt('%1 %2: %3 %4', inventSum.ItemId, inventDim.InventSerialId, inventSum.PhysicalInvent, inventSum.Picked));
break;
}
}
Here you aggreate PhysicalInvent and picked, and you can apply a having-filter using the query method addHavingFilter.
However, you cannot have that combined with another having-filter using a SQL or-statement.
If you try with a query expression, you will get a run-time error.
What you can do is create two views with each filter, then combine them using a union view. This is tricky but doable.
The first should select positive PhysicalInvent and the second should select PhysicalInvent == 0 and positive Picked.

how to avoid duplicate values in db context object in asp.net core

ALTER PROC [dbo].[rendertutorials](#courname nvarchar(30))
AS
BEGIN
SELECT
tu.FkCategoryid AS Fcatid
,tu.Title
,tu.content
,tu.Keywords
,tu.Metadata
,tu.tags
,cat.CategoryName
,cat.CourseName
,cat.courseimagepath AS imgpath
FROM GetCategories AS cat
INNER JOIN GetTutorials AS tu ON cat.CategoryId = tu.FkCategoryId
WHERE tu.publish = 1 AND cat.coursename LIKE '%' + #courname + '%'
END
GO
EXEC[rendertutorials] "mvc"
AS you can see the store procedure will produce the correct data. item[0] ... item[n] are different.
public IActionResult Tutorials()
{
//var data = GetTableLastChanges("listoftitiles #title", 1, "#title");
var data = db.getrenderview.FromSqlRaw("rendertutorials #courname={0}", "mvc").ToList();
return View(data);
}
But when I call the stored procedure from code the above data variable contain the same data (from item[0] till item[n]). Why? What did I miss?
use distinct in sql:
SELECT DISTINCT column1, column2, ...
FROM table_name;

Can SQLite return the id when inserting data?

I'm using sqlite3.exe to execute queries against my DB, using the following code.
public static string QueryDB(string query)
{
string output = System.String.Empty;
string error = System.String.Empty;
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "C:\\sqlite\\sqlite3.exe";
startInfo.Arguments = "test.db " + query;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
try
{
using(System.Diagnostics.Process sqlite3 = System.Diagnostics.Process.Start(startInfo))
{
output = sqlite3.StandardOutput.ReadToEnd();
error = sqlite3.StandardError.ReadToEnd();
sqlite3.WaitForExit();
}
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.ToString());
return null;
}
return output;
}
I'm inserting data into a table, and I'd like it to return the id of the inserted data. Is there a way to get SQLite to do this?
For example, my query might look like this "INSERT INTO mytable (some_values) VALUES ('some value');". After this query is run, I'd like output to contain the rowid of the inserted data. Is there any way to do this (a command line switch, etc.)?
A possible workaround, is to run two commands against the DB. First insert the data, then get the last inserted row id. In which case, the query would look like this "\"INSERT INTO mytable (some_values) VALUES ('some value'); SELECT last_insert_rowid();\""
You should not use max(id) or similar function in DB.
In this specific case it can work, under the condition that you use ONE connection and ONE thread to write data to DB.
In case of multiple connections you can get wrong answer.
From version SQLite 3.35.0 it supports returning close in the insert statement (SQLite Returning Close)
create table test (
id integer not null primary key autoincrement,
val text
);
insert into table test(val) values (val) returning id;
Would you consider this:
select max(id) from your_table_name;
or embedded function last_insert_rowid()?

Insert the newset value in a table and drop the old ones

I have a method which saves somes records for a machine in a table. However, I may insert by accident multiple times the records for the same machine in a day, so I want for this day to save the newest insert and drop the old ones. I thought one solution:
String sq = "SELECT date, idMachine "
+ "FROM MACHINES_RECORDS WHERE date = ? AND idMachine = ?";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
do {
//call an another method to drop this value
} while(rs.next());
}else {
//call an another method to insert this value
}
}catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null)
stm.close();
if (c != null)
c.close();
}
Is there any better/smartest solution from this, so I can make all theses actions in the same method?
With a unique index (possibly the primary key) on date and idmachine you would use INSERT ... ON DUPLICATE KEY UPDATE, so as to insert when there is no entry for that machine on that day or update the existing record with the new data otherwise.
insert into machines_records
(machineid, date, data)
values
(#id, #date, #data)
on duplicate key update data = #data;
EDIT: I see you removed the MySQL tag. So you want an answer for SQLite. In SQLite you'd use INSERT OR REPLACE:
insert or replace into machines_records
(machineid, date, data)
values
(#id, #date, #data);

Convert Linq to SQL

I have researched on the net and most result are converting from sql to linq and seldom have linq to sql.
this is the code which I want to convert to SQL :
using (CommerceEntities db = new CommerceEntities())
{
try
{
var query = (from ProductOrders in db.OrderDetails
join SelectedProducts in db.Products on ProductOrders.ProductID
equals SelectedProducts.ProductID
group ProductOrders by new
{
ProductId = SelectedProducts.ProductID,
ModelName = SelectedProducts.ModelName
} into grp
select new
{
ModelName = grp.Key.ModelName,
ProductId = grp.Key.ProductId,
Quantity = grp.Sum(o => o.Quantity)
} into orderdgrp where orderdgrp.Quantity > 0
orderby orderdgrp.Quantity descending select orderdgrp).Take(5);
RepeaterItemsList.DataSource = query;
RepeaterItemsList.DataBind();
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Load Popular Items - " +
exp.Message.ToString(), exp);
}
}
You can attempt to run the LINQ statement in LinqPad. For examples on how to use LinqPad, check the answer here.
It has a tab to show the generated SQL statement.
Here's an article on logging in LINQ to SQL. It lets you specify a TextWriter to which to send the query.
Basically, you can write something like this:
db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
... where db is your data context.
In SQL you'd write something like this (although the produced code will look a lot different, since it is auto-generated):
SELECT TOP 5 Products.ModelName, Products.ProductID, SUM(OrderDetails.Quantity) qty
FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
GROUP BY Products.ProductID, Products.ModelName
HAVING qty > 0
ORDER BY qty DESC

Resources