I have a table with a column ReceivedOn of type DateTime. I am executing a stored procedure with select statement like this:
Select
CONVERT(DateTime,ReceivedOn)[Date/Time], MessageText[Event]
From
RawFeed
Where
ATM = (Select Code From ATM Where ATM = #ATMID)
AND ReceivedOn Between #From And #To
Order By
ReceivedOn Desc
I am storing stored procedure result in a DataTable object. and showing this object on my .aspx page
dtReturn = sspObj.ExecuteDataTable();
return dtReturn ;
DataTable object is converting into HTML table using some function storing result in table object and adding that to the page
tOutput = Generix.convertDataTable2HTMLTable(dtOutput, true, true, false);
Page.Controls.Add(tOutput);
But instead of displaying values as
2012-10-05 16:40:35.234
I get output like this:
2012-10-05 04:40:35 PM
It's not a SQL issue; SQL is returning a datetime, which is getting formatted by C# into the output you are seeing. If you want SQL server to return a varchar (string) representing the date in your format, try:
SELECT CONVERT(varchar(24), ReceivedOn, 121)
See Cast and Convert for more details.
Don't convert it, leave it as is.
Select ReceivedOn, ...
select
CONVERT(varchar,CONVERT(Date,ReceivedOn,101)) + ' ' +
convert(varchar,CONVERT(TIME,ReceivedOn)) AS ReceivedDate,
CONVERT(DateTime,ReceivedOn)[Date/Time], MessageText[Event]
From
RawFeed
Where
ATM = (Select Code From ATM Where ATM = #ATMID)
AND ReceivedOn Between #From And #To
Order By
ReceivedOn Desc
Try this may this will help you....
Related
I have a table in my database that stores data entry. theres a name column where each persons name is inserted as they scan a serial number, 3 middle columns for serial entry and the last column is the date.
database sample:
i have a winform with a datagridview that populates the dates in the column header for every day of the month. what i am trying to figure out is how to populate the distinct name along with the count of their serial numbers based on what day it is in the datagridview. i can populate the names but the serial counts on specific days is getting me.
Here is what my winform looks like:
and the code:
DateTime dt = DateTime.Now;
var startDate = new DateTime(dt.Year, dt.Month, 1);
int days = DateTime.DaysInMonth(dt.Year, dt.Month);
for (int i = 0; i < days; i++)
{
dataGridView1.Columns.Add("clm_" + startDate.ToShortDateString(), startDate.ToString("dd-MMM"));
startDate = startDate.AddDays(1);
}
using (SqlConnection sqlConnection = new SqlConnection(#"connection"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT DISTINCT NAME FROM repair_data_entry", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReaderName = sqlCmd.ExecuteReader();
while (sqlReaderName.Read())
{
dataGridView1.Rows.Add(sqlReaderName["NAME"].ToString());
}
sqlReaderName.Close();
}
what i need to do is pull the serial count per day per tech. like Bill Berrys serial count for a specific day shows up in that specific cell. it may be a thing where i need to set the database up differently, i don't know. and that wouldn't be a problem. i should note there aren't specific names either. there's going to be 20-30 names that change on a daily basis so my intent was something dynamic.
EDIT:
I've been fiddling with SQL fiddler and I found the query that works! However, I had to hard code the dates. How would I make them dynamic based on what's in the CREATED column since techs will be entering in data on a daily basis?
Here's the query:
SELECT NAME AS TECH,
[12/1/2020], [12/2/2020]
FROM
(SELECT NAME, REP, CREATED
FROM repair_data_entry) AS SourceTable
PIVOT
(
COUNT(REP)
FOR CREATED IN ([12/1/2020], [12/2/2020])
) AS PivotTable;
http://sqlfiddle.com/#!18/8bc96/1
I figured out the sql Query:
DECLARE #Date AS VARCHAR(MAX),
#query AS VARCHAR(MAX)
select #dATE = STUFF((SELECT ',' + QUOTENAME(REPLACE(CONVERT(VARCHAR(10), CREATED, 101), '-', '/'))
from repair_data_entry
group by CREATED
ORDER BY CREATED
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET #query = 'SELECT NAME AS TECH, ' + #Date + '
FROM
(SELECT NAME, CREATED, REP
FROM repair_data_entry) AS S
PIVOT
(
COUNT(REP)
FOR CREATED IN ('+#Date+')
) P'
EXECUTE(#query)
This does exactly what I want. so that answers that.
sqlFiddle
can anyone point me in the direction to change the date style to "MM / dd / yyyy"?
EDIT: found the answer. updated query
I use Date as datatype in MySQL server and insert mydate as:
datetimepicker1.value.ToString("yyyy-MM-dd")
It was successfully inserted, but when I search the data using a query like:
SELECT *
FROM Customers
WHERE CDate BETWEEN datetimepicker1.Value.ToString("yyyy-MM-dd")
AND datetimepicker2.Value.ToString("yyyy-MM-dd");
It returns zero rows as result.
You forgot to use quote. Try this :
string.Format(
"SELECT * FROM Customers WHERE CDate BETWEEN '{0}'AND '{1}'",
dateTimePicker1.Value.ToString("yyyy-MM-dd"),
dateTimePicker2.Value.ToString("yyyy-MM-dd")
);
alter procedure [dbo].[XXX]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date,
#total int out
)
begin
select #total = COUNT(*)
from AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select cc.BCampaignID
from BeaconCampaign cc, VendorWorkStation vw
where cc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)
return #total
end
The above code shows the stored procedure that return an integer value from SQL Server
ObjectParameter Output = new ObjectParameter("total", typeof(Int32));
var resBC = this.Context.getTotalSentBeaconCampaign(VendorWorkstationID, sdate,edate,Output).FirstOrDefault();
The above code shows how I am passing parameters and retrieving the value on the C# side
While running the code I am getting following error
The data reader returned by the store data provider does not have
enough columns for the query requested.
What could be the possible cause for this error?
Entity Framework cannot support Stored Procedure Return scalar values out of the box.To get this to work with Entity Framework, you need to use "Select" instead of "Return" to return back the value.
More Ref : http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values
I am using Sql-Server 2012 and have a query
string sqlQuery = "SELECT distinct DATE_FORMAT(collectiondate,'%m/%d/%Y') FROM reports where patientid= " + patientId + " and isdeleted=false order by collectiondate desc";
var lst = Session.CreateSQLQuery(sqlQuery).List();
ArrayList rpt = new ArrayList();
rpt.Add("--ALL--");
but I am getting an error
System.Data.SqlClient.SqlException: 'DATE_FORMAT' is not a recognized built-in function name.
Can someone help me out?
You should rather try using CONVERT
SELECT CONVERT(VARCHAR(8),GETDATE(),1)
SQL Fiddle DEMO
That being said, I would recomend returning the values as is from the Database, and leaving the formatting to the UI.
There's no DATE_FORMAT function in SQL Server.
You need to use CONVERT function
SELECT distinct SELECT CONVERT(VARCHAR(8), collectiondate, 1) ...
Also, formatting is best to be done in the code, not in SQL Server. You should return your date as DATE or DATETIME column and format it in your code.
You can use the FORMAT() command in SQL Server 2012 instead.
DECLARE #d DATETIME = GETDATE();
SELECT FORMAT(#d, 'mm/dd/yy', 'en-US') AS 'Result';
Here is my code for passing table value pair to stored procedure.
DOJ field is DateTime and in SP, DOJ field is date. Both are compatible. Output is like dd/MM/yyyy.
If DOJ field is DateTime and in SP, DOJ field is DateTime2(3), o/p is dd/MM/yyyy hh:mm:ss
But I need o/p to be dd/MM/yyyy. How should i write the code ?
dt1.Columns.Add("DOJ", typeof(System.DateTime));
DataRow dr1 = dt1.NewRow();
dr1["DOJ"] = DateTime.ParseExact("02/03/2001", formats, us, DateTimeStyles.None);
// dr1["DOJ1"] = "12/13/2001"; if i use this one it works .
dt1.Rows.Add(dr1); // Get DOJ as - 3/2/2001 12:00:00 AM
ds1.Tables.Add(dt1);
Here is my stored procedure code -
-- CREATE TYPE StateTbls7 AS TABLE
( StateID VARCHAR(200)
, StateCode VARCHAR(200)
, StateName VARCHAR(200)
, DOJ date
)
ALTER PROCEDURE sp_Add_contact
(
#ds1 StateTbls7 readonly
)
AS
begin
declare #DOJ VARCHAR(200)
select #DOJ = d1.DOJ from #ds1 d1
select #DOJ as 'a1'
end
return
Remove 'formats' declaration
Instead, change like this in your c#,
dr1["DOJ"] = DateTime.ParseExact("02/03/2001", us, DateTimeStyles.None).ToString("d");
Hope it may help.Let me know the result.
Try to change you SQL query like this
....Code before this
select #StateID = d1.StateID
,#StateCode = d1.StateCode
,#DOJ = convert(varchar(15), d1.DOJ, 103) -- 103 is dd/MM/yyyy
from #ds1 d1
....Rest of the Code
here i cast the date time to text and removed the time
HOPE THIS HELP!