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!
Related
I am currently having a problem printing the output using C# asp.net. I've built a stored procedure containing a query that will select the username if the login date and time that the user is trying to login on the website is in between a specific start and end time. So here is my code using sql server:
CREATE PROCEDURE [dbo].[access]
(#DateNow as varchar(50),
#studentnum as varchar(50)
)
AS
IF EXISTS(SELECT StudentNum
FROM users, enlistment
WHERE StudentNum LIKE '13%'
AND #DateNow BETWEEN '2016-09-28 00:00:00.000' AND endtime)
SELECT username FROM users, enlistment
WHERE StudentNum LIKE '13' + #studentnum
AND #DateNow BETWEEN starttime AND endtime
Here is my code in c#
SqlCommand cmd3 = new SqlCommand("access", connection);
SqlParameter useraccess = new SqlParameter("studentnum", fourNum);
string datenow = DateTime.Now.ToString("MMMM dd yyyy hh:mm");
SqlParameter date = new SqlParameter("DateNow", datenow);
cmd3.Parameters.Add(useraccess);
cmd3.Parameters.Add(date);
cmd3.CommandType = CommandType.StoredProcedure;
lblStatus.Text = Convert.ToString(cmd3.ExecuteScalar());
After executing, lblStatus.Text should display the username of the person trying to login. unfortunately, the website is not showing it. Is there a problem in my code?
This is a fix on your use of Date, not an answer as to why you are not getting the expected result.
Always use the native data types in .net and sql server, never a string representation of the type!
Changed sp signature
CREATE PROCEDURE [dbo].[access]
(#DateNow as Date, -- change this to Date or DateTime or DateTime2 accordingly
#studentnum as varchar(50)
)
-- rest of stored proc does not have to change
Changed c# code
SqlParameter date = new SqlParameter("#DateNow", SqlDbType.Date) {Value = System.DateTime.Now.Date};
// or with time
// SqlParameter date = new SqlParameter("#DateNow", SqlDbType.DateTime) {Value = System.DateTime.Now};
I have a method that requires 3 string so:
public <List> MethodName(string date1, string date2, string number)
{
//
}
in my database date1 and date2 are stored as DateTime and number is stored as Int so how would I write a SQL query that will search based on these three parameters?
I have converted my date1 and date2 like this:
DateTime firstdate = Convert.ToDateTime(date1);
string fdate = firstdate.ToLongDateString();
DateTime seconddate = Convert.ToDateTime(date1);
string sdate = seconddate .ToLongDateString();
My SQL query is:
SELECT * From TableName
WHERE [Time] > #date1 AND
[Time] < #date2 AND [StaffCode] =#StaffCode;
command.Parameters.AddWithValue("#date1", fdate);
command.Parameters.AddWithValue("#date2", sdate );
command.Parameters.AddWithValue("#StaffCode", number);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{ get the data ...}
I am sure that my SQL query is wrong.
Since your database columns are already strongly typed, just ensure that your C# parameters are typed as System.DateTime and int (System.Int32) respectively before binding them to your query. Your sql is then simply:
SELECT col1, col2, col3
FROM TableName
WHERE [Time] > #date1 AND
[Time] < #date2 AND [StaffCode] =#StaffCode;
If you allow for inclusive dates, you can use BETWEEN, i.e.
WHERE [Time] BETWEEN #date1 AND #date2
AND [StaffCode] = #StaffCode
i.e. avoid the need to convert a Date to a string altogether. Wherever possible, try and keep a strong type system all the way through your code, both C# and SQL - this will save a lot of pain during conversion. e.g. if possible, see if you can change the signature to:
public List<MethodName>(DateTime date1, DateTime date2, int number)
{
// Bind the DateTimes, not a string!
command.Parameters.AddWithValue("#date1", date1);
command.Parameters.AddWithValue("#date2", date2);
command.Parameters.AddWithValue("#StaffCode", number);
Edit Don't use SELECT * - use SELECT Col1, Col2, ...
Conversion:
DateTime firstdate = Convert.ToDateTime(date1);
string fdate = firstdate.ToString("yyyy-MM-dd");
DateTime firstdate2 = Convert.ToDateTime(date2);
string fdate2 = firstdate2.ToString("yyyy-MM-dd");
SQL Query:
#"SELECT * From TestTable WHERE Time BETWEEN CONVERT(Date,#date1) AND CONVERT(Date,#date2) AND StaffCode=CONVERT(int,#StaffCode)"
command.Parameters.AddWithValue("#date1", fdate);
command.Parameters.AddWithValue("#date2", fdate2);
command.Parameters.AddWithValue("#StaffCode", number);
I'm trying to compare a C# DateTime with a SQL-server DateTime in a Stored Procedure but it keeps giving me convert-errors.
At first someone else made the Oracle function for this:
'Select blabla from bla WHERE (TO_DATE (''' + cast(#dateEnd as varchar(50)) + ''',''yyyy/mm/dd'') >= SPOT_ENDDAT)
And I'm trying to change this to SQL but in SQL you don't have the TO_DATE function.
Any ideas? Or should I make the changes at the level of my .net program itself? If yes, what should I do?
EDIT:
Calling my function Stored Procedure with this parameter :
DateTime EndDate = DateTime.Today;
ParamList.Add(new <class>.Parameter("EndDate", ParameterDirection.Input, EndDate, DbType.Date));
Stored Procedure:
ALTER PROCEDURE dbo.uspGetValues
#EndDate = null;
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL as NVARCHAR(4000)
Set #SQL = 'SELECT * FROM T_SPOTSHOP_DATA WHERE SPOT_ENDDATE IS NOT NULL'
if(#EndDate is not null)
Set #SQL = #SQL + 'AND (' + #EndDate +' <= SPOT_ENDDATE'
EXEC(#SQL)
Edit Solution:
For those who have the same problem I fixed it the other-way around. In C# I would used :
DateTime EndDate = DateTime.Today.toString(yyyy-MM-dd);
ParamList.Add(new <class>.Parameter("EndDate", ParameterDirection.Input, EndDate, DbType.Date));
and I catch it up in my stored procedure as:
EndDate Varchar(50)
SET #SQL = #SQL + 'WHERE CONVERT(DATETIME, '''+ #EndDate +''', 121) >= SPOT_ENDDATE
It's a quite ugly way to do it but it works. Hopes it helps you guys!
try this:
Select
blabla
from
bla
WHERE CAST(#dateEnd AS DATETIME) >= CAST(SPOT_ENDDAT AS DATETIME)
You can perform the conversion in T-SQL using CONVERT, but I wouldn't.
I would strongly recommend avoiding string conversions as far as possible. Just use parameterized SQL, and specify the parameter as a DateTime:
// Assuming dateEnd is a DateTime variable
string sql = "SELECT blabla FROM bla WHERE #dateEnd >= SPOT_ENDDAT";
using (var command = new SqlCommand(conn, sql))
{
command.Parameters.Add("#dateEnd", SqlDbType.DateTime).Value = dateEnd;
// Execute the command here
}
I'd do the equivalent for Oracle as well - unless your task really inherently involves converting between text and the "native" data type, don't do it.
Or use a LINQ provider of course, at which point you'll have a more readable query to start with :)
Just pass the .Net DateTime value as a parameter to the Sql Command. The database driver will handle the conversion to an Sql Server date time automatically.
I have code like this:
AutoParkDataDataContext Db = new AutoParkDataDataContext();
Dailyreport dailyRep = new Dailyreport();
string time = Convert.ToDateTime("10-10-2014 15:00:00");
dailyRep.order_time = time;
Db.Dailyreports.InsertOnSubmit(dailyRep);
Db.SubmitChanges();
When I see it in the DailyReport table it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored. How could i fix it?
The column type is DateTime.
A quick/easy method to insert date or datetime into MySQL is to use the format 'yyyy-MM-dd', or datetime as 'yyyy-MM-dd H:mm:ss'.
Try this
DateTime theDate = DateTime.Now;
theDate.ToString("yyyy-MM-dd H:mm:ss");
Make your SQL look like this.
insert into mytable (date_time_field) value ('2013-09-09 03:44:00');
Your line:
string time = Convert.ToDateTime("10-10-2014 15:00:00");
Shouldn't compile.
I can only guess that you don't have DateTime as type of your column in SQL Server, you should modify it to keep DateTime and then pass a DateTime type object, not a string.
This means that the underlying data type in the database must be Date. Change that to DateTime and it will store the time as well.
DateTime dateTimeVariable = DateTime.Now;
string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss");
The insert Statement will look kind of like this:
string InsertQuery = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";
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....