SQL Server - Multiple Select with Duplicate Names - sql

I'm trying to grab some data from my SQL database as below;
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC
The problem is when I read the data I get an error 'Name'.
Dim byWeight As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
Dim byAge As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
How would I read this data as above considering I can't use name twice?

I think you are missing a semi-colon after the first SELECT statement. Here's a sample app I put together (note the semicolon in my sql statement):
var sql = "Select TOP 1 name from sys.columns;"
+ "Select TOP 1 name from sys.objects";
var firstname = string.Empty;
var secondname = string.Empty;
var connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using ( var conn = new SqlConnection( connString ) )
{
conn.Open();
using ( var cmd = new SqlCommand( sql, conn ) )
{
var reader = cmd.ExecuteReader();
if ( reader == null )
return;
if ( reader.Read() )
firstname = reader.GetString( reader.GetOrdinal( "Name" ) );
reader.NextResult();
if ( reader.Read() )
secondname = reader.GetString( reader.GetOrdinal( "Name" ) );
}
}
Response.Write( firstname + "<br />" );
Response.Write( secondname + "<br />" );
You can achieve the same goal as the semi-colon by using the "GO keyword like so:
var sql = "Select TOP (1) name from sys.columns GO "
+ "Select TOP (1) name from sys.objects";

You can use the 'as' keyword to rename columns in your results, like so:
SELECT TOP(1) [Name] AS ByWeight FROM [Peeps] ORDER BY [Weight] DESC

hmmm... well you could make it one select statement....
USE exampleDatabase
SELECT W.[Name] AS W_Name, A.[Name] AS A_Name FROM
(SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC) W
JOIN (SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC) A

What if you UNION your SQL together into one result set?
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
UNION ALL
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC

Related

Account for empty fields

Is there a way to count empty fields with this query by adding somewhere Nz, IIf(IsNull()), or something similar?
SELECT DISTINCTROW
mytable.[field1],
mytable.[field2],
mytable.[field3]
FROM mytable
WHERE (((mytable.[field1]) In (SELECT [field1] FROM [mytable] As Tmp GROUP BY
[field1],
[field2],
[field3]
HAVING Count(*)>1 And
[field1] = [mytable].[field1] And
[field2] = [mytable].[field2] And
[field3] = [mytable].[field3]
)));
returns nothing because there are empty fields in field3.
Is there a way to put
IIf(IsNull(field3), "emptyfield", field3)
or something similar somewhere in the query, so that empty field3's will be taken into account?
Try with one or two Nz:
Nz([field1], [mytable].[field1]) = [mytable].[field1]
' or:
[field1] = Nz([mytable].[field1], [field1])
' or:
Nz([field1], [mytable].[field1]) = Nz([mytable].[field1], [field1])
' or, if text:
Nz([field1], "") = Nz([mytable].[field1], "")
' or, if numeric:
Nz([field1], 0) = Nz([mytable].[field1], 0)

How to solve this error of conversion failed?

I am getting this error
Conversion failed when converting the varchar value 'Thowheed' to data type int.
I visited and checked in stack overflow, but I couldn't find answer
I added values in drop down list, once I select and click ok button it has to show me the record from database.
This is my code
string cs = ConfigurationManager.ConnectionStrings["Nibrass_DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Date as Date,Credit, Debit_From as Received_From, Credit_Amount as amount, Reason From Transaction_Credit where Credit = " + DropDownListSelectAccount.SelectedValue+ " or cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + " ORDER BY Date DESC";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
DateTime dt = Convert.ToDateTime(rd[0]);
string receivedFrom = rd[1].ToString();
int amount = Convert.ToInt32(rd[2]);
}
con.Close();
}
My database table definition is
CREATE TABLE [dbo].[Transaction_Credit]
(
[Date] DATE NOT NULL,
[Credit] VARCHAR (50) NOT NULL,
[Debit_From] VARCHAR (50) NOT NULL,
[Reason] VARCHAR (100) NULL,
[Credit_Amount] INT NOT NULL,
[Balance] INT NULL
);
You should not be concatenating your string. This is a bad practice and your code becomes vulnerable to SQL Injection.
You should use parameters instead:
cmd.CommandText = #"
SELECT Date
, Credit
, Debit_From AS Received_From
, Credit_Amount AS Amount
, Reason
FROM Transaction_Credit
WHERE Credit = #DropDownListSelectAccount
OR Debit_From = #DropDownListSelectAccount
ORDER BY Date DESC";
cmd.Parameters.Add("#DropDownListSelectAccount", SqlDbType.VarChar, 50). Value) = DropDownListSelectAccount.SelectedValue;
By the way, you don't need to cast Debit_From as a varchar, since it's already like that in your database.
This is your query:
select Date as Date, Credit, Debit_From as Received_From,
Credit_Amount as amount, Reason
from Transaction_Credit
where Credit = " + DropDownListSelectAccount.SelectedValue+ " or
cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + "
order by Date DESC;
The code reading this is:
int amount = Convert.ToInt32(rd[2]);
But the 3rd column is Received_From, not amount. That is probably your problem.
Also, cast(Debit_From as varchar) is very dangerous. When you don't include a length for varchar(), SQL Server inserts a length depending on the context. Just don't do a conversion where you don't need one.

SqlCommand: Incorrect syntax near the keyword 'OVER'

I'm trying to get data from database show it in a ASP.NET DataGrid.
It's showing the above mentioned error.
This is the select command:
public MasterJobList GetListForGrid(int RecCount, int PageNo, string OrderBy)
{
strSql = "WITH TempTable AS(Select JobDetails.JobCode,JobDetails.CurrentStatus,MasterModel.Name As ModelNumber,MasterModel.Code As ModelCode,MasterBrand.Code As BrandCode,MasterBrand.Name As BrandName,MasterDeviceType.Code As DeviceCode,MasterDeviceType.Name As DType,ROW_NUMBER() OVER (ORDER BY " + OrderBy + ") AS RowNumber From JobDetails JobDetails Inner Join MasterDeviceType ON JobDetails.DType = MasterDeviceType.Code Inner Join MasterBrand ON JobDetails.BCode = MasterBrand.Code Inner join MasterModel ON JobDetails.ModelNumber = MasterModel.Code WHERE 1 = 1) SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
MasterJobList objList = new MasterJobList();
DataTable dt = new DataTable();
dt = objDB.GetDataTableFromSQL(strSql);
if (dt != null)
{
foreach (DataRow Dr in dt.Rows)
{
jobs obj = new jobs();
obj.JobCode =Convert.ToInt32(Dr["JobCode"].ToString());
if (Dr["DType"] != DBNull.Value)
obj.DType = Dr["DType"].ToString();
else
obj.DType = "";
if (Dr["BrandName"] != DBNull.Value)
obj.BrandName = Dr["BrandName"].ToString();
else
obj.BrandName = "";
if (Dr["ModelNumber"] != DBNull.Value)
obj.ModelNumber = Dr["ModelNumber"].ToString();
else
obj.ModelNumber = "";
if (Dr["CurrentStatus"] != DBNull.Value)
obj.CurrentStatus = Dr["CurrentStatus"].ToString();
else
obj.CurrentStatus = "";
objList.Add(obj);
}
}
return objList;
}
The exact error is:
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'OVER'.
Please look my full code...
Your ROW_NUMBER-"column" comes after the JOINs.
Change it to:
string sql = #"
WITH TempTable AS
(
Select
JobDetails.JobCode,
JobDetails.CurrentStatus,
MasterModel.Name As ModelNumber,
MasterModel.Code As ModelCode,
MasterBrand.Code As BrandCode,
MasterBrand.Name As BrandName,
MasterDeviceType.Code As DeviceCode,
MasterDeviceType.Name As DType,
ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber
From JobDetails JobDetails
Inner Join MasterDeviceType
ON JobDetails.DType = MasterDeviceType.Code
Inner Join MasterBrand
ON JobDetails.BCode = MasterBrand.Code
Inner join MasterModel
ON JobDetails.ModelNumber = MasterModel.Code,
WHERE {1}
)
SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
Now use sql = String.Format(sql, orderBy, filter, rnStart, rnEnd) to assign the values.
The variables could be:
string orderBy = "ModelNumber ASC";
string filter = "BrandName = 'Sony'";
int rnStart = PageNo == 1 ? 1 : ((PageNo - 1) * RecCount) + 1;
int rnEnd = PageNo == 1 ? RecCount : PageNo * RecCount;
Update: to show the complete method (at least the relevant code) according to your edit.
public MasterJobList GetListForGrid(int RecCount, int PageNo, string OrderBy)
{
string strSql = #"
WITH TempTable AS
(
Select
JobDetails.JobCode,
JobDetails.CurrentStatus,
MasterModel.Name As ModelNumber,
MasterModel.Code As ModelCode,
MasterBrand.Code As BrandCode,
MasterBrand.Name As BrandName,
MasterDeviceType.Code As DeviceCode,
MasterDeviceType.Name As DType,
ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber
From JobDetails JobDetails
Inner Join MasterDeviceType
ON JobDetails.DType = MasterDeviceType.Code
Inner Join MasterBrand
ON JobDetails.BCode = MasterBrand.Code
Inner join MasterModel
ON JobDetails.ModelNumber = MasterModel.Code,
WHERE {1}
)
SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
int rnStart = PageNo == 1 ? 1 : ((PageNo - 1) * RecCount) + 1;
int rnEnd = PageNo == 1 ? RecCount : PageNo * RecCount;
strSql = String.Format(strSql, OrderBy, "1=1", rnStart, rnEnd);
DataTable dt = objDB.GetDataTableFromSQL(strSql);
// ...
return objList;
}
please check this example in ssms and change the accordingly.
declare #t table(name varchar(50))
insert into #t values ('a'),('b'),('c'),('d'),('e')
select ROW_NUMBER() over ( order by name)
, name
from #t
Check the comment, you just apply the "orderby" by value
WITH temptable
AS (SELECT jobdetails.jobcode,
jobdetails.currentstatus,
mastermodel.NAME AS ModelNumber,
mastermodel.code AS ModelCode,
masterbrand.code AS BrandCode,
masterbrand.NAME AS BrandName,
masterdevicetype.code AS DeviceCode,
masterdevicetype.NAME AS DType,
Row_number()
OVER (
ORDER BY " + orderby + ") AS RowNumber --here you have to assign the order by value
FROM jobdetails JobDetails
INNER JOIN masterdevicetype
ON jobdetails.dtype = masterdevicetype.code
INNER JOIN masterbrand
ON jobdetails.bcode = masterbrand.code
INNER JOIN mastermodel
ON jobdetails.modelnumber = mastermodel.code
WHERE 1 = 1)
SELECT *
FROM temptable
WHERE rownumber BETWEEN {2} AND {3}

Error in JPQL Query: "unexpected token: ( near line 1"

i have this working sql query:
select temp.pratica_regola_id FROM ( SELECT TABLE1.pratica_regola_id, TABLE1.CON FROM ( SELECT pratica_regola_id, COUNT(*) AS CON FROM (SELECT DISTINCT PRATICA_REGOLA_ID, ENTITA_LEGAME_ID FROM legame_regola_pratica L1 LEFT JOIN (select LRP.entita_legame_id AS EL1 from legame_regola_pratica LRP JOIN entita_legame EL ON LRP.entita_legame_id = EL.entita_legame_id where LRP.pratica_regola_id = 418 AND LRP.REGOLA_ID = 1426 AND el.tp_entita_legame_id =1 ) TAB_ENT_LEG ON TAB_ENT_LEG.EL1 = L1.entita_legame_id WHERE TAB_ENT_LEG.EL1 IS NOT NULL AND l1.tp_livello_legame_id = 2 and l1.pratica_regola_id in (select pratica_regola_id from pratica_regola where tp_stato_pratica_id = 2)) GROUP BY PRATICA_REGOLA_ID ) TABLE1 INNER JOIN ( SELECT pratica_regola_id, COUNT(*) AS TOT FROM (SELECT DISTINCT PRATICA_REGOLA_ID, ENTITA_LEGAME_ID FROM legame_regola_pratica L1) group by pratica_regola_id) TABLE2 on TABLE1.pratica_regola_id = TABLE2.pratica_regola_id where TABLE1.CON = TABLE2.TOT) temp WHERE CON = (SELECT COUNT(*) FROM legame_regola_pratica where pratica_regola_id = 418 AND REGOLA_ID = 1426 and dat_ora_can is null) and pratica_regola_id <> 418;
I tried to tranlsate it in JPQL in this kind:
#Query("SELECT TABLE_TEMP_1.praticaRegolaId FROM ("
+ "SELECT TABLE_TEMP_2.praticaRegolaId, TABLE_TEMP_2.numero_entita FROM ("
+ "SELECT praticaRegolaId, COUNT(*) AS numero_entita FROM (SELECT DISTINCT PraticaRegola.praticaRegolaId, EntitaLegame.entitaLegameId FROM LegameRegolaPratica LRP_1 LEFT JOIN ("
+ "SELECT LRP.entitaLegame.entitaLegameId AS EL_1 FROM LegameRegolaPratica LRP JOIN EntitaLegame EL ON LRP.entitaLegame.entitaLegameId = EL.entitaLegameId"
+ "WHERE LRP.praticaRegola = :praticaRegola AND LRP.regola = :praticaRegola.regola AND EL.tpEntitaLegame = :tipoEntitaLegame)"
+ "TAB_ENT_LEG ON TAB_ENT_LEG.EL_1 = LRP_1.entitaLegame.entitaLegameId WHERE TAB_ENT_LEG.EL_1 IS NOT NULL AND LRP_1.tpLivelloLegame = :tipoLivelloLegame AND LRP_1.praticaRegola.praticaRegolaId IN (SELECT praticaRegolaId FROM"
+ " praticaRegola WHERE tpStatoPratica = :tipoStatoPratica))"
+ "GROUP BY praticaRegolaId) AS TABLE_TEMP_2"
+ "INNER JOIN ("
+ "SELECT praticaRegolaId, COUNT(*) AS TOT FROM (SELECT DISTINCT LRP_1.praticaRegola.praticaRegolaId, LRP_1.entitaLegame.entitaLegameId FROM LegameRegolaPratica LRP_1) GROUP BY praticaRegolaId"
+ ") TABLE_TEMP_3" + "ON TABLE_TEMP_2.praticaRegolaId = TABLE_TEMP_3.praticaRegolaId" + "WHERE TABLE_TEMP_2.NUMERO_ENTITA = TABLE_TEMP_3.TOT )"
+ "AS TABLE_TEMP_1 WHERE NUMERO_ENTITA = (SELECT COUNT(*) FROM LegameRegolaPratica WHERE praticaRegola = :praticaRegola"
+ "AND regola = :praticaRegola.regola AND dataOraCancellazione IS NULL) ")
but i get this error message:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 42 [SELECT TABLE_TEMP_1.praticaRegolaId FROM (SELECT TABLE_TEMP_2.praticaRegolaId, TABLE_TEMP_2.numero_entita FROM (SELECT praticaRegolaId, COUNT(*) AS numero_entita FROM (SELECT DISTINCT PraticaRegola.praticaRegolaId, EntitaLegame.entitaLegameId FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP_1 LEFT JOIN (SELECT LRP.entitaLegame.entitaLegameId AS EL_1 FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP JOIN EntitaLegame EL ON LRP.entitaLegame.entitaLegameId = EL.entitaLegameIdWHERE LRP.praticaRegola = :praticaRegola AND LRP.regola = :praticaRegola.regola AND EL.tpEntitaLegame = :tipoEntitaLegame)TAB_ENT_LEG ON TAB_ENT_LEG.EL_1 = LRP_1.entitaLegame.entitaLegameId WHERE TAB_ENT_LEG.EL_1 IS NOT NULL AND LRP_1.tpLivelloLegame = :tipoLivelloLegame AND LRP_1.praticaRegola.praticaRegolaId IN (SELECT praticaRegolaId FROM praticaRegola WHERE tpStatoPratica = :tipoStatoPratica))GROUP BY praticaRegolaId) AS TABLE_TEMP_2INNER JOIN (SELECT praticaRegolaId, COUNT(*) AS TOT FROM (SELECT DISTINCT LRP_1.praticaRegola.praticaRegolaId, LRP_1.entitaLegame.entitaLegameId FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP_1) GROUP BY praticaRegolaId) TABLE_TEMP_3ON TABLE_TEMP_2.praticaRegolaId = TABLE_TEMP_3.praticaRegolaIdWHERE TABLE_TEMP_2.NUMERO_ENTITA = TABLE_TEMP_3.TOT )AS TABLE_TEMP_1 WHERE NUMERO_ENTITA = (SELECT COUNT(*) FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica WHERE praticaRegola = :praticaRegolaAND regola = :praticaRegola.regola AND dataOraCancellazione IS NULL) ]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
Thank you
You may not have subqueries in the from clause of a HQL query. Use a native SQL query.
Quote from the documentation:
Note that HQL subqueries can occur only in the select or where clauses.

SQL into LINQ... need a nudge in the right direction

I want to use LINQ as a DataGrivdView Datasource... I have the correct SQL query, but I'm having a heck of a time re-writing it in LINQ...
SQL:
SELECT ICITEM.ITEMNO, ICITEM.[DESC], MAX(PORCPL.DTARRIVAL) AS Expr1
FROM ICITEM INNER JOIN
PORCPL ON PORCPL.ITEMNO = ICITEM.ITEMNO
WHERE (ICITEM.ITEMNO LIKE '%R001%')
GROUP BY ICITEM.ITEMNO, ICITEM.[DESC]
My feeble attempt(s) at LINQ:
Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Select [Item_ID] = items.ITEMNO, [Description] = items.DESC, [rd] = recDates.DTARRIVAL
My LINQ Log...
SELECT [t0].[ITEMNO] AS [Item_ID], [t0].[DESC] AS [Description], [t1].[DTARRIVAL] AS [rd]
FROM [dbo].[ICITEM] AS [t0]
INNER JOIN [dbo].[PORCPL] AS [t1] ON [t0].[ITEMNO] = [t1].[ITEMNO]
WHERE ([t0].[ITEMNO] LIKE #p0) OR ([t0].[DESC] LIKE #p1)
-- #p0: Input VarChar (Size = 8000; Prec = 0; Scale = 0) [%r001%]
-- #p1: Input VarChar (Size = 8000; Prec = 0; Scale = 0) [%r001%]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
I can't figure out how to get a Max function on the [rd] field... ANY insight would be most appreciated.
You need to add a Group By.
Here is an example which should help:
Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Group By items.ITEMNO, items.DESC Into MaxArrivalDate = Max(recDates.DTARRIVAL)
Select [Item_ID] = items.ITEMNO, [Description] = items.DESC, [rd] = MaxArrivalDate
You have an additional Contains in your linq query. If this is correct, here is the full linq query with group by and max:
Dim s = From items In db.ICITEMs
Where items.ITEMNO.Contains(Me.txtQuery.Text) Or items.DESC.Contains(Me.txtQuery.Text)
Join recDates In db.PORCPLs On items.ITEMNO Equals recDates.ITEMNO
Group By items.ITEMNO, items.DESC Into Group
Let MaxArrival = Group.Max(Function(p) p.recDates.DTARRIVAL)
Select [Item_ID] = ITEMNO, [Description] = DESC, [rd] = MaxArrival