Cache-SQL ZDATETIME function in SQL? - sql

What function can I use (similar to ZDATETIME() in ObjectScript) in Cache SQL to translate from a seconds from epoch timestamp to a UTC timestamp? I looked into the documentation and could only find information on doing this in Object Script... What function can you use in the SQL? Thanks!

I think you're looking for something like this;
DECLARE #epoch INT
SET #epoch = 1348519792
SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), GETDATE()), DATEADD(s, #epoch, '19700101 00:00:00:000'))
SQL Fiddle

Figured it out, I had to convert it all manually. I spent forever trying to find a pre-existing function, but here is how I did it:
select
TO_CHAR(substr(audit.stamp,1,5),'YYYY-MM-DD') AS Date,
CASE LEN(CAST(substr(audit.stamp,7)/3600 AS INT))
WHEN 2 THEN CAST(substr(audit.stamp,7)/3600 AS INT)
ELSE '0' || CAST(substr(audit.stamp,7)/3600 AS INT)
END || ':' ||
CASE LEN(CAST((substr(audit.stamp,7)/60)#60 AS INT))
WHEN 2 THEN CAST((substr(audit.stamp,7)/60)#60 AS INT)
ELSE '0' || CAST((substr(audit.stamp,7)/60)#60 AS INT)
END || ':' ||
CASE LEN(CAST(substr(audit.stamp,7)#60 AS INT))
WHEN 2 THEN CAST(substr(audit.stamp,7)#60 AS INT)
ELSE '0' || CAST(substr(audit.stamp,7)#60 AS INT)
END AS Time
from utility.audit
As taken from the Cache SQL Reference Manual:
CLOCKTIME
NEW
SET Time=$PIECE($HOROLOG,",",2)
SET Sec=Time#60
SET Totmin=Time\60
SET Min=Totmin#60
SET Milhour=Totmin\60
IF Milhour=12 { SET Hour=12,Meridian=" pm" }
ELSEIF Milhour>12 { SET Hour=Milhour-12,Meridian=" pm" }
ELSE { SET Hour=Milhour,Meridian=" am" }
WRITE !,Hour,":",Min,":",Sec,Meridian
QUITCLOCKTIME
NEW
SET Time=$PIECE($HOROLOG,",",2)
SET Sec=Time#60
SET Totmin=Time\60
SET Min=Totmin#60
SET Milhour=Totmin\60
IF Milhour=12 { SET Hour=12,Meridian=" pm" }
ELSEIF Milhour>12 { SET Hour=Milhour-12,Meridian=" pm" }
ELSE { SET Hour=Milhour,Meridian=" am" }
WRITE !,Hour,":",Min,":",Sec,Meridian
QUIT
Thanks!

Related

Error occurs when trying to convert nvarchar to date mssql node js

I'm trying to query a SQL Server from node js, using the mssql module. The date format in the database is dd/mm/yyyy hh:mm:ss. The query works just fine from SQL Server Management Studio, but it generates the following error when used in node.js:
Here is the code:
//This query aims to retrieve the records that have been inserted to the database in the last 5 min
var sq = "SELECT * FROM [ofm1].[dbo].[ass_site] WHERE CONVERT(datetime, date1) > DATEADD(MINUTE, -5, GETDATE());"
conn = new mssql.ConnectionPool(dbConfig);
conn.connect().then(function () {
var request = new mssql.Request(conn);
request.query(sq).then(function (recordSet) {
recordSet = recordSet.recordset;
recordSet = JSON.stringify(recordSet)
recordSet = JSON.parse(recordSet)
recordSet.forEach(function(row) {
console.log("row:nevr: " + row.nevr)
console.log("row:group id " + row.codeass)
var rq = new mssql.Request(conn);
rq.input('id', mssql.NChar, row.nevr)
rq.input('group', mssql.NChar, row.codeass)
rq.input('feedback', mssql.Text, "new ticket !")
rq.input('url', mssql.NChar, "")
rq.input('notified', mssql.TinyInt, 0)
rq.query("INSERT INTO [ofm1].[dbo].[ticket] values (#id, #group, #feedback, #url, #notified);").then(function() {
});
});
/* console.log(recordSet);
console.log("description: " + recordSet.name);*/
// conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
Any help will be greatly appreciated, many thanks!!!
usually this error happens when trying to convert date not well formatted
for example try to convert date of format mm/dd/yyyy using dd/mm/yyyy format
SELECT CONVERT(datetime, '06/18/2018 12:05:23',103)
result:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
but if it is well formatted as following will working fine
SELECT CONVERT(datetime, '18/06/2018 12:05:23',103)
result:
2018-06-18 12:05:23.000
specify format code of your date to be 103 to match your date format dd/mm/yyyy as following:
//This query aims to retrieve the records that have been inserted to the database in the last 5 min
var sq = "SELECT * FROM [ofm1].[dbo].[ass_site] WHERE CONVERT(datetime, date1,103) > DATEADD(MINUTE, -5, GETDATE());"
for more details about format code check following link

MVC SignalR TSQL Issue With DateTime

I'm trying to migrate from ASP.NET WebForms to MVC and have used this example
which worked fine using SQL Server 2008 Express hosted on an Azure VM. However once I modified the SQL from the "Step 6: Get the Data from the Repository" section of the tutorial:
public class MessagesRepository
{
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public IEnumerable<Messages> GetAllMessages()
{
var messages = new List<Messages>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage = reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub.SendMessages();
}
}
}
Which I changed the SQL to this:
#"SELECT [AssignedToUser], [Status], [RequestID] FROM [dbo].[Notifications] WHERE AssignedToUser IS NOT NULL AND Status IS NOT NULL AND RequestID IS NOT NULL AND AssignedToUser = 'Kyle G' AND Status = 'Red'
Which worked fine but when I wanted to get only notifications stamped with today's date and appended my SQL:
AND CAST(TimeStatusChange AS DATE) = CONVERT(date, getdate())
Or even this:
AND TimeStatusChange >= (GetDate() - 1)
It fails to update unless you refresh the page. Any ideas friends?
Note-TimeStatusChange is a datetime field.
I converted the current day and database field "TimeStatusChange" as such:
SELECT convert(varchar(25), TimeStatusChange, 120) AS TimeStatusChange, [Id],[AssignedToUser], [Status], [RequestID] FROM [dbo].[Notifications] WHERE AssignedToUser IS NOT NULL AND Status IS NOT NULL AND RequestID IS NOT NULL AND AssignedToUser = 'Kyle G' AND Status = 'Red' AND convert(varchar(25), getdate(), 112) = convert(varchar(25), TimeStatusChange, 112) ORDER BY TimeStatusChange DESC
It should be noted that the issue remains and is not that the SQL when run VS 2015 or SSMS does not work it does. It also works on a page refresh of the MVC page. It does not push the new record to the page in real time without a page refresh.
Here is the results in SSMS using Convert for both the TimeStatusChange and getdate() objects:
In other words if I do this (Essentially an "If 1==1" test):
SELECT TimeStatusChange FROM [dbo].[Notifications] WHERE convert(varchar(25), TimeStatusChange, 112) = convert(varchar(25), TimeStatusChange, 112)
SignalR Updates the page upon INSERT of new record.
If I change it to compare the DB field to today's date as strings:
SELECT TimeStatusChange FROM [dbo].[Notifications] WHERE convert(varchar(25), TimeStatusChange, 112) = convert(varchar(25), getdate(), 112)
SignalR no longer updates the page on INSERT new record unless I refresh it. The SQL works it just breaks SignalR from updating the page without a refresh.
If I do the opposite If 1==1 test by comparing today's date to itself as a string:
SELECT TimeStatusChange FROM [dbo].[Notifications] WHERE convert(varchar(25), getdate(), 112) = convert(varchar(25), getdate(), 112)
This also breaks SignalR from updating the page UNLESS I refresh the page. The clue seems to be a problem with:
convert(varchar(25), getdate(), 112)
Breaking SignalR, not the SQL. Perhaps this is too difficult to troubleshoot without having the full solution available.
To answer your question " Do you have a suggestion as to how to get today's date as just the date and no time as a date?"
Here is how you would convert the dates:
SELECT CONVERT(VARCHAR(10),GETDATE(),112),CONVERT(VARCHAR(10),GETDATE(),111),CONVERT(VARCHAR(10),GETDATE(),110)
and the results:
I finally got it (Thanks to Kamran & Dan for hints). I do not understand why this worked but by passing the current date into the SQL statement as a string as opposed to using getdate() or DATEADD in SQL made it work! Why is beyond my pay grade.
Here is the working code (yes I will parameterize it!)
string dateof = DateTime.Today.ToString("MM/dd/yyyy");
connection.Open();
using (var command = new SqlCommand(#"SELECT [Id],[AssignedToUser], [Status], [RequestID] FROM [dbo].[Notifications] WHERE '" + dateof + "' = convert(varchar(25), TimeStatusChange, 101) ORDER BY TimeStatusChange DESC", connection))

SQL query date string by range

Spec: I need to query by date month and day only (ignoring year)
Input:
start := '2015-12-29'
end := '2016-01-03'
Output:
1986-12-30
1980-01-01
1982-12-31
1978-01-03
...
Current solution:
SELECT *
FROM users
WHERE RIGHT(birthday,5) >= $1
AND RIGHT(birthday,5) <= $2
But this only works when the year not overlap, what's the easiest solution for this case?
My simplest solution is by generating the SQL string using another language:
if start_year == end_year {
date_where = `
AND RIGHT(birth_date,5) >= RIGHT(` + Z(start) + `,5)
AND RIGHT(birth_date,5) <= RIGHT(` + Z(end) + `,5)
`
} else {
date_where = `
AND ( RIGHT(birth_date,5) >= RIGHT(` + Z(start) + `,5)
AND RIGHT(birth_date,5) <= '12-31'
) OR ( RIGHT(birth_date,5) >= '01-01'
AND RIGHT(birth_date,5) <= RIGHT(` + Z(end) + `,5)
)`
}
I believe there are better way than this..
A date is not a string, don't use string functions to handle a date. Use date functions like EXTRACT:
SELECT '2015-12-29'::date,
EXTRACT(month from '2015-12-29'::date),
EXTRACT(day from '2015-12-29'::date);

Stored procedure expects parameter that is being passed

From the following code I get the error that #StartDate is not supplied, however stepping through the two date range parameters have a valid value:
SqlParameter[] ps = new SqlParameter[]
{
new SqlParameter("#StartDate", startDate),
new SqlParameter("#EndDate", endDate)
};
List<AttendanceReportViewModel> res = db.Database.SqlQuery<AttendanceReportViewModel>(Local.queries["AttendanceReport"], ps).ToList();
return res;
The stored procedure :
ALTER PROCEDURE [dbo].[GetAttendanceReport]
#StartDate datetime,
#EndDate datetime
AS
BEGIN
SET NOCOUNT ON;
exec [REMOTE_SRV].LWD.dbo.ReportAttendance_sp #StartDate = #StartDate, #EndDate = #EndDate;
END
Everything works fine when I execute the stored procedure in SQL Server Management Studio but doesn't from within the application.
If your Local.queries["AttendanceReport"] looks something like this:
Local.queries["AttendanceReport"] = "yourProc #StartDate, #EndDate"
Then try this:
List<AttendanceReportViewModel> res = db.Database.SqlQuery<AttendanceReportViewModel(
Local.queries["AttendanceReport"],
new SqlParameter("StartDate", startDate),
new SqlParameter("EndDate", endDate)
).ToList();

Remove a particular character from varchar while retrieving data using query

I want to remove a particular character while retrieving a varchar from a table. The query looks like this:
SELECT ServiceName,
case isNumeric(Ramusage)
when 1 then
cast ( ltrim ( rtrim ( ramusage )) as int )
else
0
end as test,
priority
FROM ProcessInfo
Here the problem is ramusage is a varchar and it stores values like 12,500K, 4,321K.
Here I want to remove the "K" from the entry and display the number alone.
You want to use the REPLACE function:
REPLACE(ramusage, 'k', '')
Reference:
SQL Server
Oracle
MySQL
Use REPLACE
DECLARE #ProcessInfo TABLE(
ServiceName VARCHAR(MAX),
Ramusage VARCHAR(MAX),
priority INT
)
INSERT INTO #ProcessInfo (ServiceName,Ramusage,priority)
SELECT 'TEST','12,123K',1
SELECT ServiceName,
case isNumeric(REPLACE(REPLACE(Ramusage,'K',''),',',''))
when 1 then
cast ( ltrim ( rtrim ( REPLACE(REPLACE(Ramusage,'K',''),',',''))) as int )
else
0
end as test,
priority
FROM #ProcessInfo
what we have done is to create a CLR function to take a string amd remove all non numeric items
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString RemoveNonNumeric(SqlString strValue)
{
string strNew = strValue.ToString();
char[] chrArray = strNew.ToCharArray();
strNew = null;
for (int iChar = 0; iChar < chrArray.Length; iChar++)
{
if (Char.IsNumber(chrArray[iChar]))
strNew += chrArray[iChar];
}
// Put your code here
return new SqlString(strNew);
}
substr( ltrim( rtrim( ramusage ) ), length( ramusage ) - 1)
edit: replace, as mentioned in the other answers, is probably better.