Last value selection in SQL-Server - c#

I am trying to select last values of the columns in the datatable from the SQL Server Database.
My code is
private void bind_chart()
{
// here i am using SqlDataAdapter for the sql server select query
SqlDataAdapter adp = new SqlDataAdapter("select last() * from Test", con);
// here am taking datatable
DataTable dt = new DataTable();
try
{
// here datatale dt is fill wit the adp
adp.Fill(dt);
// this string m catching in the stringbuilder class
// in the str m writing same javascript code that is given by the google.
// my data that will come from the sql server
// below code is same like as google's javascript code
str.Append(#" <script type='text/javascript'>
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');");
// inside the below line dt.Rows.Count explain that
// how many rows comes in dt or total rows
str.Append("data.addRows(" + dt.Rows.Count + ");");
Int32 i;
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
// i need this type of output " data.setValue(0, 0, 'Memory'); so on in the first line so for this
//m using i for the 0,1& 2 and so on . and after this i am writting zero and after this student_name using datatable
str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i]["x"].ToString() + "');");
// i need this type of output " data.setValue(0, 1, 80);
//so on in the first line so for this
//m using i for the 0,1& 2 and so on . and after this i am writting zero and after this percentage using datatable
str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["y"].ToString() + ") ;");
// str.Append("['" + (dt.Rows[i]["student_name"].ToString()) + "'," + dt.Rows[i]["average_marks"].ToString() + "],");
}
str.Append("var chart = new google.visualization.Gauge(document.getElementById('chart_div'));");
// in the below line i am setting the height and width of the Gauge using your own requrirement
str.Append(" var options = {width: 800, height: 300, redFrom: 90, redTo: 100,");
// str.Append(" var chart = new google.visualization.BarChart(document.getElementById('chart_div'));");
str.Append("yellowFrom: 75, yellowTo: 90, minorTicks: 5};");
str.Append("chart.draw(data, options);}");
str.Append("</script>");
lt.Text = str.ToString().TrimEnd(',');
}
catch
{
}
finally
{
}
}
And want to display the last value on the gauge.
Here I am not getting the last value from the query I generated. I dont know why.

Best and recommended method.
select top 1 * from test order by ID desc

I think Last() is not a function of sql-server
But you can get the last row by using my below way's .Try this
SELECT * FROM TableName WHERE PrimaryKeyId= (SELECT MAX(PrimaryKeyId) FROM TableName )
or , try another way.
SELECT TOP 1 * FROM TableName ORDER BY PrimaryKeyId DESC
make sure set identity for your primary key .

SQL Server doesn't support LAST() syntax. Instead you can use another approach described here - http://www.w3schools.com/sql/sql_func_last.asp

Related

how to join two tables in sql and showing the results event A then all attendees, Event B and showing all the attendees, etc

Good Afternoon All,
I am creating an admin page that shows a list of events and those who volunteered to help. I have one table for events and another for those who are volunteer.
I stored the eventID into the volunteer's table and am able to join them, but when i join them I get a new row for each volunteer which also shows the event name again.
I would like to display the event name and underneath the event name show the volunteers.
ex.
event A
Volunteer 1
volunteer 2
volunteer 3
event B
Volunteer 1
volunteer 2
Can anyone point me in the right direction?
public string volunteers(){
SqlCommand cmd = new SqlCommand(#"SELECT* FROM fundraiser_youth
LEFT JOIN
fundrasier_helpers ON fundraiser_youth.id = fundrasier_helpers.eventID
ORDER BY reportTime;", con);
con.Open();
SqlDataReader reader;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime reportTime = Convert.ToDateTime(reader[1]);
DateTime gateTime = Convert.ToDateTime(reader[2]);
DateTime gameTime = Convert.ToDateTime(reader[3]);
VOLUNTEER.Append("<div class='col-md-4'>");
VOLUNTEER.Append("<div class='well well-lg'>");
VOLUNTEER.Append("<form action='register/default.aspx' method='POST'>");
VOLUNTEER.Append("<h4>" + reportTime.DayOfWeek + " " + reportTime.Month + "/" + reportTime.Day + "/" + reportTime.Year + "</h4>");
VOLUNTEER.Append("<h5>" + reader[4].ToString() + " " + reader[7].ToString() + " " + reportTime.ToString("h:mm tt", CultureInfo.InvariantCulture) + "</h5>");
VOLUNTEER.Append("<ul>");
VOLUNTEER.Append("<li>" + reader[10].ToString() + " " + reader[11].ToString() + "</li>");
VOLUNTEER.Append("</ul>");
VOLUNTEER.Append("<input type=hidden name='id' value='" + reader[8].ToString() + "' />");
VOLUNTEER.Append("<span style='text-align:right; margin-top:20px;'><input type='submit' value='Register' class='btn btn-info' /></span>");
VOLUNTEER.Append("</form>");
VOLUNTEER.Append("</div>");
VOLUNTEER.Append("</div>");
}
return VOLUNTEER.ToString();
}
return "no info provided";
}
The first aspect of your stated problem is the select list. Select * will return all columns of all joined tables in the query for each joined row. So, each of your helpers will have the fundraising event information as part of its row data.
One side note for maintenance: select * is a bad habit for "production code", especially if you're getting fields out of the result set by index (which you are), because if you add a field to fundraiser_youth, all the indexes representing fields from fundraiser_helpers will no longer line up with the result set being returned, and your UI and any validation logic on this field data will break. I recommend strongly that you either specify the list of desired columns explicitly, get them out of reader using the column names instead of index positions, or both.
Since you're digesting the results programmatically in C#, the easiest solution to your stated problem is to first change your ORDER BY clause so that rows are sorted by fundraiser_youth.id before anything else. Then, get the event information once on the first row, generate your event header and the first volunteer row in HTML, remember that event ID, and check it against the ID of subsequent rows as you iterate through the reader generating the rest of the volunteer HTML rows. As long as the event IDs match, ignore the event fields and only extract/display the helper fields. When they differ, the event has changed and you need to re-retrieve the event information for the next sub-header.
Here is how I ended up fixing my problem. May not be best option but it works, Thanks for everyone's input and in the production code I replaced the select * with the columns. I made a new function called (loadHelpers) and pass the id of the current Event to it. This function pulls all the volunteers who signed up to help.
public string volunteers()
{
SqlCommand cmd = new SqlCommand(#"SELECT * FROM fundraiser_youth WHERE reportTime >='" + DateTime.Now + "' ORDER BY reportTime" , con);
con.Open();
SqlDataReader reader;
try
{
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime reportTime = Convert.ToDateTime(reader["reportTime"]);
DateTime gateTime = Convert.ToDateTime(reader["gateTime"]);
DateTime gameTime = Convert.ToDateTime(reader["gameTime"]);
events.Append("<div class='col-md-4'>");
events.Append("<div class='well well-lg'>");
events.Append("<form action='register/default.aspx' method='POST'>");
events.Append("<h4>" + reportTime.DayOfWeek + " " + reportTime.Month + "/" + reportTime.Day + "/" + reportTime.Year + "</h4>");
events.Append("<h5>" + reader["eventName"].ToString() + " " + reader["location"].ToString() + " " + reportTime.ToString("h:mm tt", CultureInfo.InvariantCulture) + "</h5>");
events.Append(loadHelpers(reader["id"].ToString()));
events.Append("<!--<span style='text-align:right; margin-top:20px;'><input type='submit' value='Edit' class='btn btn-info' /></span>-->");
events.Append("</form>");
events.Append("</div>");
events.Append("</div>");
}
return events.ToString();
}
return "no info provided";
}
catch (Exception e)
{
return "ERROR" + e;
}
}
public string loadHelpers(string id)
{
var cmd2 = new SqlCommand(#"SELECT * FROM fundrasier_helpers WHERE eventID='"+ id + "'" , con2);
con2.Open();
if (cmd2.ToString() != "")
{
SqlDataReader reader2;
StringBuilder helper = new StringBuilder();
helper.Append("<ul>");
try
{
reader2 = cmd2.ExecuteReader();
if (reader2.HasRows)
{
while (reader2.Read())
{
helper.Append("<li>" + reader2["firstName"] + " " + reader2["lastName"] + " " + reader2["phone"] + " " + reader2["shirtSize"] + "</li>");
}
}
reader2.Close();
}
catch (Exception e)
{
helper.Append("<li>No volunteers have signed up " + e + "</li>");
}
helper.Append("</ul>");
con2.Close();
return helper.ToString();
}
else
{
return "<ul><li>No volunteers have signed up</li></ul>";
}
}

Duplicate values of every data row

There are 2 rows in my table and I'm receiving values within my site as follows:
I should only be receiving 2 rows so I'm not sure what I've done wrong with my code?
if (binForm.Rows.Count != 0)
{
int rowCounter = binForm.Rows.Count;
int increment = 0;
while (rowCounter > 0)
{
tableData.Append("<tr><td>" + binForm.Rows[increment]["binType"].ToString() + "</td><td>" + binForm.Rows[increment]["binColour"].ToString() + "</td><td>" + binForm.Rows[increment]["date"].ToString() + "</td><tr>");
increment++;
rowCounter--;
}
}
This is how the form is generated:
DataTable binForm = new DataTable();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter("SELECT bin.binType, bin.binColour, missedbin.date FROM bin INNER JOIN missedbin ON missedbin.address_addressID=bin.address_addressID WHERE '" + sessionVarAddress.ToString() + "' = bin.address_addressID ", connect);
dataAdapter.Fill(binForm);
here is the actual data in the bin table.
and missedbin table.
EDIT: It seems as though as suggested my sql query is incorrect as it is returning 4 rows.
The problem will be the join, not this snip-it of code.
if you join on a field with 2 entries the same, it will double up as per this example. please go back and check your query.

c# sql wildcard not working

I am attempting to use "%" in order to search for a range of dates. In the table the dates are of the format "03/01/2015" and I am trying to return data for all dates of a specific month (03/2015 for example).
I am creating two strings of the format...
String datePrev1 = monthLast + "%";
String datePrev2 = "%" + yearLast;
Where datePrev1 == "03%" and datePrev2 == "%2015" which I have confirmed to be generating correctly.
My SQL search method is...
SqlCommand selectCommand = new SqlCommand("SELECT project, prevWeekHours FROM submissionsHours WHERE (WWID = '" + ID + "' AND (datePrevWeek LIKE '" + datePrev1 + "' AND datePrevWeek LIKE '" + datePrev2 + "'))", Conn1);
Conn1.Open();
SqlDataReader reader = selectCommand.ExecuteReader();
int totalTime = 0;
while (reader.Read() == true)
{
project.Add(reader[0].ToString());
projTime.Add(Convert.ToInt32(reader[1]));
totalTime += Convert.ToInt32(reader[1]);
}
Conn1.Close();
int index = project.Count; //total amount of projects
testLabel.Text = index.ToString() + "..." + datePrev1+datePrev2;
The testLabel.Text I have for troubleshooting is returning 0 for the index indicating there were no matches for this string when there are certainly entries in the table that should match it.
Any ideas on what I am doing wrong?
I have attempted querying like...
... WHERE datePrevWeek LIKE '03/__/2015';
... WHERE datePrevWeek LIKE '03____2015';
To no success... Thanks.
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND (YEAR(datePrevWeek)*100)+MONTH(datePrevWeek) = #YEARMONTH
#YEARMONTH should be of format 201503 representing march 2015.
Using parameters will avoid sql injection.
When datePrevWeek is varchar
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND right(datePrevWeek,7) = #YEARMONTH_STR
#YEARMONTH_STR is of format '01/2015'
Once you store dates in the format '2015-03-13',...
Plan A: WHERE dt LIKE '2015%'
Plan B (This is more efficient, given a suitable index):
WHERE dt >= CONCAT('2015', '-01-01')
AND dt < CONCAT('2015', '-01-01') + INTERVAL 1 YEAR
(I'm assuming '2015' is filled in by the code.)
Try Below:
Declare #Dat Date
set #Dat = '03/01/2015'
SELECT CAST(MONTH(#Dat) AS VARCHAR(2)) + '/' + CAST(YEAR(#Dat) AS VARCHAR(4)) AS [DD/YYYY]

all_ind_expressions view of Oracle

I'm trying to execute the below query through OracleDataReader in .NET but when I try to read the value of the column_expressions column, I always get an empty string.
SELECT ic.column_name,
ie.column_expression
FROM all_ind_columns ic
LEFT JOIN all_ind_expressions ie
ON ie.index_owner = ic.index_owner
AND ie.index_name = ic.index_name
AND ie.column_position = ic.column_position
WHERE ic.index_owner = 'owner_name'
AND ic.index_name = 'index_name'
I realized that the datatype of the column id is LONG but I'm not sure if that's the reason. Is there a way I can read the actual value of the column?
When I execute the same query through Oracle SQL developer, I can see the value.
To be able to read a column that is of LONG data type the InitialLONGFetchSize property of OracleCommand has to be set to a none zero(zero by default) value:
Unfortunately you did not provide your .NET code, so I'll give you a C# + ODP.NET unmanaged driver example:
Set-up:
create table t1(
col1 varchar2(11)
);
create index FBI on t1(upper(col1));
table T1 created.
index FBI created.
C# code:
string oraConnectionString = "Data source=nkpdb;User id=hr;password=password;";
OracleConnection oraConnection = new OracleConnection(oraConnectionString);
oraConnection.Open();
/* Would be better to put this in a stored procedure */
string sqlQuery = "select ic.column_name " +
" , ie.column_expression " +
" from all_ind_columns ic " +
" left join all_ind_expressions ie " +
" on ie.index_owner = ic.index_owner " +
" and ie.index_name = ic.index_name " +
" and ie.column_position = ic.column_position " +
" where ic.index_owner = :INDOwner " +
" and ic.index_name = :INDName" ;
OracleCommand oraCmd = new OracleCommand(sqlQuery, oraConnection);
OracleParameter indOwner = new OracleParameter("INDOwner",
OracleDbType.Varchar2);
OracleParameter indName = new OracleParameter("INDName",
OracleDbType.Varchar2);
indOwner.Value = "HR";
indName.Value = "FBI";
oraCmd.Parameters.Add(indOwner);
oraCmd.Parameters.Add(indName);
/* set up initial amount of data that the OracleDataReader
* fetches for LONG column */
oraCmd.InitialLONGFetchSize = 1000; /* set initial size */
OracleDataReader oraDataReader = oraCmd.ExecuteReader();
if (oraDataReader.HasRows)
{
while (oraDataReader.Read())
{
Console.WriteLine(oraDataReader.GetString(
oraDataReader.GetOrdinal("column_expression")));
}
}
Result:
By default the InitialLONGFetchSize property is set to 0. That's the reason why you are getting an empty string. So you either need to set this property to a value greater than zero or set it to -1 to fetch an entire LONG column.
Here 's another simple solution.
1 - Create this function
create or replace function Get_Text
(sINDEX_NAME in VARCHAR2, sIndex_owner in VARCHAR2, sColumn_position in VARCHAR2)
return varchar2
is
Long_to_Varchar varchar(32767);
begin
select COLUMN_EXPRESSION into Long_to_Varchar
from SYS.all_ind_expressions
where INDEX_NAME = sINDEX_NAME and Index_owner=sIndex_owner and Column_position=sColumn_position;
return long_to_varchar;
exception
when others then
return 'Error occurred';
end;
2 - Use this SQL
select ic.index_name,
ic.column_name,
GET_TEXT(Ie.INDEX_NAME,Ie.Index_owner,ie.Column_position )
from all_ind_columns ic
left join all_ind_expressions ie
on ie.index_owner = ic.index_owner
and ie.index_name = ic.index_name
and ie.column_position = ic.column_position
WHERE ic.index_owner = 'owner_name'
AND ic.index_name = 'index_name'

Special Character does not displays in gridview from SQL database with Parameter

Well I have tried all you people suggested but the problem remain same
let me tell you in brief:
Form Name : ​AuzineForum.aspx
Has 1 GridView which displays all the field from the database using ​ select * from QF
its working good , index is also working , the gridView Has Button and onClick I open new Form ​AuzineForumAnswer.aspx​ ..OK
I want to pick one record from ​AuzineForum.aspx​ and display on AuzineForumAnswer.aspx as well as it happens here in http://stackoverflow.com (we click on threads then the new page opens which has the question and answer on which we clicked previous) ...ok
so On AuzineForum.aspx's Button the code is
Button lb = (Button)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
if (row != null)
{
int index = row.RowIndex; //gets the row index selected
Label AID1 = (Label)ForumQuesView.Rows[index].FindControl("AID1");
Label AID2 = (Label)ForumQuesView.Rows[index].FindControl("AID2");
Label AID3 = (Label)ForumQuesView.Rows[index].FindControl("AID3");
HyperLink Question = (HyperLink)ForumQuesView.Rows[index].FindControl("Question");
Label Questiontags = (Label)ForumQuesView.Rows[index].FindControl("Questiontags");
Label Askedby = (Label)ForumQuesView.Rows[index].FindControl("Askedby");
Response.Redirect(String.Format("AuzineForumAnswer.aspx?Question=" + Question.Text + "&Questiontags=" + Questiontags.Text + "&Askedby=" + Askedby.Text + "&AID1=" + AID1.Text + "&AID2=" + AID2.Text + "&AID3=" + AID3.Text, Server.UrlEncode(Question.Text), Server.UrlEncode(Questiontags.Text), Server.UrlEncode(Askedby.Text), Server.UrlEncode(AID1.Text), Server.UrlEncode(AID2.Text), Server.UrlEncode(AID3.Text)));
I had passes so many many parameter becuase of accuracy......
Now when I run it and click on the button so its open ​AuzineForumAnswer.AuzineForumAnswerand shows that record very well but problem occurs when the qtags field has "#" type of data like here tags( ​C#, GridView, etc) so, ​ when the tags field has the data includin "#" chracter then it gives "​Object refrence not set to Instance of an object " and if the qtags has normal data like ( specialcharacter gridview sql C ) then it open AuzineForumAnswer.​aspx​ and show data without error
the code behind of AuzineForumAnswer.aspx is below
protected void GetAllData()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = sqlconn.CreateCommand())
{
sqlcomm.CommandText = "Select * From QF where Question='" + Server.UrlDecode(Request.QueryString["Question"].ToString()) + "' And qtags='" + Server.UrlDecode(Request.QueryString["Questiontags"].ToString()) + "' And UserFullName='" + Server.UrlDecode(Request.QueryString["Askedby"].ToString()) + "' And AID1='" + Server.UrlDecode(Request.QueryString["AID1"].ToString()) + "' And AID2='" + Server.UrlDecode(Request.QueryString["AID2"].ToString()) + "' And AID3='" + Server.UrlDecode(Request.QueryString["AID3"].ToString()) + "'";
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
try
{
sqlconn.Open();
ForumQuesView.DataSource = dt;
ForumQuesView.DataBind();
ForumQuesView.AllowPaging = true;
}
catch (Exception ex)
{
Status.Text = ex.Message.ToString();
}
}
}
}
NOW I ALSO DO NOT UNDERSTAND What the problem here because only qtags and question is two field in which user allows to store data as they want, the ​question ​is text and qtags and all are the char field but problem is not in database the problem is here with the character #
Try changing your sql statement to include parameters and see if that works.
What you have now is not only difficult to maintain and causes errors but it’s prone to SQL injection attack quite easily.
sqlcomm.CommandText = "Select * From QF where Question=#Question And qtags=#Qtags And UserFullName=#UserName And AID1=#AID1 And AID2=#AID2 And AID3=#AID3";
sqlcomm.Parameters.Add(new SqlParameter("#Question", Server.UrlDecode(Request.QueryString["Question"])));
sqlcomm.Parameters.Add(new SqlParameter("#Qtags", Server.UrlDecode(Request.QueryString["Questiontags"])));
sqlcomm.Parameters.Add(new SqlParameter("#UserName", Server.UrlDecode(Request.QueryString["Askedby"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID1", Server.UrlDecode(Request.QueryString["AID1"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID2", Server.UrlDecode(Request.QueryString["AID2"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID3", Server.UrlDecode(Request.QueryString["AID3"])))
;
As I know the query is fine even if you using # in the condition.
I doubt for a moment, then I tried this query
Select * From QF where Question='question 1'
And qtags='tag #1';
those query still run smooth and return the record.

Categories