Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Getting this code error when executing the following code.. Help would be appreciated
DECLARE #Last_Timestamp DATETIME,
#New_Timestamp DATETIME
SELECT DISTINCT Rtrim(of_displayname) + ' ('
+ Rtrim(ro_officer) + ')',
CONVERT(DATETIME, CONVERT(CHAR(11), ro_shift_start, 106), 106),
Rtrim(ac_name) + ' (' + Rtrim(ac_pin) + ')',
ro_officer
FROM roster WITH(nolock),
template WITH(nolock),
activity WITH(nolock),
officer WITH(nolock)
WHERE ro_status = 'INFO'
AND ro_activity IN ( 'LEAVE', 'SAL LEAVE' )
AND ro_timestamp > #Last_Timestamp
AND ro_timestamp <= #New_Timestamp
AND ro_shift_start > Getdate()
AND ac_pin = to_activity
AND to_pin = ro_officer
AND Unicode(to_type) = Unicode('M')
AND ro_officer = of_pin
--AND (Of_Payroll_No IN ('w','s')
AND ac_product_code IN ( '01', '09' ) /* Corporate Only */ /* W & S */
UNION
SELECT [officer],
[activity],
[status],
[comment]
FROM production.rolecall.[dbo].[holidayrequest]
ORDER BY Rtrim(of_displayname) + ' ('
+ Rtrim(ro_officer) + ')',RTRIM(Of_Displayname) + ' (' + RTRIM(Ro_Officer) + ')',CONVERT(DATETIME,CONVERT(CHAR(11), RO_Shift_Start,106),106)
There are 3 places where you are doing date conversions here:
CONVERT(DATETIME, CONVERT(CHAR(11), ro_shift_start, 106), 106)
CONVERT(DATETIME,CONVERT(CHAR(11), RO_Shift_Start,106),106)
the UINON
The first two look like you are actually trying to get the day without the time. If so: get the day without the time; there are various ways of doing this, but in recent versions of sql server, casting it to a date would work fine:
select cast(columnname as date) as [columnname]
or if you really need it as datetime:
select cast(cast(columnname as date) as datetime) as [columnname]
On other database versions you can use the sneeky "cast it as a float" approach:
select cast(floor(cast(columnname as float)) as datetime) as [columnname]
The UNION is more interesting; it looks like these are very different shapes - in which case: why are you unioning them? I very much doubt that [activity] is a datetime, yet that is the column it will become part of. It is entirely possible that this error is coming from trying to convert [activity] to a datetime.
Related
I am writing Insurance Managment System as project at University.
This is my MySQL commadn:
string lifeQuery = "insert into lifeinsurance values( null, '" + surname.Text + "." + pesel.Text + "', " + double.Parse(lifeInsSumTB.Text) + ", '" + double.Parse(lifeInsPriceTB.Text)
+ ");";
But te problem is that in UWP double is with ',' and to MySQL i need to have it with '.'.
When I try to do this like this: '25,453' it says data truncated. Without ' ', like this 25,453 it says that column count doesn't match value count at row 1, because it interets it as two different values 25 and 453.
So my question is:
How do I insert this double value to my table?
This problem is caused by the implicit conversion to a string when you call double.Parse and then concatenate the result back into the sql text. This requires the compiler to represent the double value as a string and it will use the current culture to do the conversion. Of course the result is not what MySql expect to be a double value.
Moreover using string concatenation to build sql commands leads to Sql Injection hacks. A very nasty problem that you should avoid. Always.
So let's try to add some code to resolve these problems
// A parameterized string without any concatenation from user input
string lifeQuery = #"insert into lifeinsurance
values( null, #surname, #sum, #price)";
MySqlCommand cmd = new MySqlCommand(lifeQuery, connection);
// Add the parameters with value for each placeholder in string
cmd.Parameters.AddWithValue("#surname", surname.Text + "." + pesel.Text);
// Parse the user input as a double using the current culture to correctly
// interpret the comma as decimal separator.
// Note that here I have no check on the correctness of the input. If your
// user cannot be trusted to type a valid double number then you should use
// the double.TryParse approach separating these lines from the actual check
cmd.Parameters.AddWithValue("#sum", double.Parse(lifeInsSumTB.Text, CultureInfo.CurrentCulture));
cmd.Parameters.AddWithValue("#price", double.Parse(lifeInsPriceTB.Text, CultureInfo.CurrentCulture));
cmd.ExecuteNonQuery();
Like other said - there are better ways to send over data with Sql. That being said this answer focuses on addressing your specific problem.
I think your problem may be your language/culture settings.
Try this:
Console.WriteLine(double.Parse("19.2323244").ToString("G", CultureInfo.InvariantCulture));
Output:
19.2323244
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netcore-3.1#Invariant
can you help me because i want to display on the report viewer the dates that has no data recorded or inserted........ for example.. MARCH 2,3,5,7 has record.. i want to display on the report viewer that has no record MARCH 4,6.....something like that.
enter image description here
you can use this code to build up your calendar then just a matter of join the calendar to your table
declare #mm varchar(2) = '02'
declare #yy varchar(4) = '2017'
select cast(#yy + '-' + #mm + '-' + cast(x.dd as varchar(2)) as date)
from
(select number [dd] from master..spt_values
where type = 'p'
and number between 1 and 31
) x
where isdate(cast(#yy + '-' + #mm + '-' + cast(x.dd as varchar(2)) as varchar(max))) = 1
order by x.dd
I'm currently working on a search method in C# for a SQL Server database.
The regex:
/(a)|(b)|(c)|(d)/g
a, b, c & d are the search keywords.
The string that I apply the regex to:
a fdh eidb
Consists of random words(represented as letters) and some of the keywords from above.
Expected output:
3 keywords matches.
But how does a SQL query for SQL Server look like that returns a table with a Matches column with the keyword match count for each row?
I know how to do this in C# but I want to do it in the search query itself so I can sort the output.
Thanks for any help towards the right direction :)
I don't think there is a way to do regular expressions in SQL Server queries - other than adding some managed code which adds that functionality.
Here is an example of how to do that - SQL Server Regular expressions in T-SQL
It seems that REGEX wasn't really the solution.
Instead I wrote multiple SQL functions that do the job:
CREATE FUNCTION [dbo].[KeywordMatches]
(
#String nvarchar(1000),
#Keywords nvarchar(1000),
#Seperator text
)
RETURNS INT
AS
BEGIN
DECLARE #Count int = 0;
DECLARE #Keyword varchar(1000);
DECLARE KeywordsCursor CURSOR FOR
SELECT *
FROM [dbo].StringSplit(#Keywords, #Seperator)
OPEN KeywordsCursor
FETCH NEXT FROM KeywordsCursor INTO #Keyword
WHILE ##FETCH_STATUS = 0
BEGIN
IF #String LIKE '%' + #Keyword + '%'
SET #Count += 1
FETCH NEXT FROM KeywordsCursor INTO #Keyword
END
CLOSE KeywordsCursor
DEALLOCATE KeywordsCursor
RETURN #Count
END
And (fallback for server 2016 split_string):
CREATE FUNCTION [dbo].[StringSplit]
(
#SeperatedWords nvarchar(1000),
#Seperator char
)
RETURNS #Words TABLE
(
Word nvarchar(1000)
)
AS
BEGIN
DECLARE #Position int = -1
SET #SeperatedWords += #Seperator
WHILE (#Position > 0 OR #Position = -1)
BEGIN
SET #SeperatedWords = SUBSTRING(#SeperatedWords, #Position + 1, LEN(#SeperatedWords) - #Position + 1)
SET #Position = CHARINDEX(#Seperator, #SeperatedWords)
/* Only add words that have a length bigger then 0 */
IF #Position > 1
/* Add the word to the table */
INSERT INTO #Words(Word) VALUES(LEFT(#SeperatedWords, #Position - 1))
END
RETURN
END
Usage:
SELECT Id, Title, [dbo].KeywordMatches(Title, 'blue red green', ' ') AS Matches
FROM Questions
ORDER BY Matches DESC, Date DESC
Above query orders by the amount of keywords found in the title and date.
I also read about full text search which is probably faster then this solution.
I have a scheduled job which runs at 12:45:00 AM. Now through SP I want to get this time. I am running this query in my SP:
EXEC msdb.dbo.sp_help_job
#job_name = N'Daily Trends',
#job_aspect = N'SCHEDULES' ;
This query shows result with a column
active_start_time
4500
Expected Output: 12:45:00 AM.
Can you please suggest how to show the time with Am/PM.
Edit: I am calling this SP from c# code. If anybody can suggest how i can convert the time in proper format in c# code will also be helpful.
As the time value seems to be stored as HHMMSS with the hour (HH) optional I think you need to check if the length of the string is four chars (or maybe if the value exceeds 115959, whichever is faster). A query like this should work:
SELECT CASE
WHEN Len(active_start_time) = 4 THEN Cast(
Dateadd(minute, active_start_time /
100, '00:00') AS TIME)
ELSE LEFT(RIGHT('0' + Cast(active_start_time AS VARCHAR), 6), 2)
+ ':'
+ Substring(RIGHT('0' + Cast(active_start_time AS VARCHAR), 6), 3,
2)
+ ':'
+ RIGHT(Cast(active_start_time AS VARCHAR), 2)
END AS [Start time]
FROM msdb..sysschedules
INNER JOIN msdb.dbo.sysjobschedules
ON msdb.dbo.sysjobschedules.schedule_id =
msdb..sysschedules.schedule_id
INNER JOIN msdb.dbo.sysjobs
ON msdb.dbo.sysjobs.job_id = msdb.dbo.sysjobschedules.job_id
WHERE msdb.dbo.sysjobs.name = 'Daily Trends'
I didn't test it with that many values but I believe it should work, or at least give you a hint on how to proceed. Accessing the msdb tables directly might be a bad idea and if I recall right, there are some views that give access to similar information and it could be better to use them.
You can use the sysjobschedules table however the date will be the same.
This blog should help parse the date/time:
http://blog.sqlauthority.com/2008/12/22/sql-server-find-next-running-time-of-scheduled-job-using-t-sql/
so, to get the data to look like a HH:MM:SS format, the following SQL would work:
SELECT LEFT(RIGHT('0' + Cast(active_start_time AS VARCHAR), 6), 2)
+ ':'
+ Substring(RIGHT('0' + Cast(active_start_time AS VARCHAR), 6), 3, 2)
+ ':'
+ RIGHT(Cast(active_start_time AS VARCHAR), 2)
FROM msdb..sysschedules
I have an SQL query :
SELECT DATEDIFF(deadline,CURDATE()) FROM tasks WHERE 1
The Result is : 3
How can I return the result as : 3 Days instead of 3
I know that I can manually append the string from my C# code something like :
string result = getSqlresult();
string result += " Days";
But I want to get the result directly as 3 Days from MySQL database.
The reason :
I'm binding information directly to datagridview and therefore, In order to modify the result i need to iterate through all rows and update them. So to increase performance, I need to get the result directly from database as 3 Days instead of 3
Anyhelp would be highly appreciated
you can concatenate the string Days into the result of DATEDIFF using CONCAT.
SELECT CONCAT(DATEDIFF(deadline,CURDATE()), ' Days')
FROM tasks
WHERE 1
if you are using old versions of MySQL, convert it to string so you will not get bolb result.
SELECT CONCAT(CAST(DATEDIFF(deadline,CURDATE()) AS CHAR(5)), ' Days')
FROM tasks
WHERE 1
UPDATE 1
SELECT CASE
WHEN DATEDIFF(deadline,CURDATE()) >= 0
THEN CONCAT(DATEDIFF(deadline,CURDATE()), ' Days')
ELSE CONCAT('Expired since ', DATEDIFF(deadline,CURDATE()) * -1, ' Days')
END
FROM tasks
SQLFiddle Demo