Find a row with nvarchar column that have a int value between two values in middle of string in column - sql

I have a nvarchar column that have values like
'21:15:00 monday 1390/09/10 morning'
I want to select rows that have a third part (meaning: '1390/09/10') between '1390/09/07' AND '1390/09/15'. I don't want to change the structure of column values to bring the third part to start or end of the string for some reasons. I tried this
SELECT * FROM table WHERE column BETWEEN '%1390/09/07%' AND '%1390/09/15%'
but it won't work.
I used SQL Server 2008.

To extract the date you have to do this:
DECLARE #t VARCHAR(100) ='21:15:00 monday 1390/09/10 morning'
SELECT CONVERT(DATETIME2, SUBSTRING(#t, PATINDEX('%[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',#t),10),111)
I used DateTime2 as I used SQL Server 2008.
I hope this help you.

Related

SQL add text to numeric column

I'm not sure if this is even possible but I have a query that joins two table and compares two data sets, current month vs previous month. Where I have new data the previous column produces a Null.
I have been trying to replace NULL with the text 'New Account'. However I am aware that I am trying to force a text value into a numeric column.
So I'm just wondering if this is even possible as I haven't found anything online to help.
Thanks in advance.
Just to expand on Gordon's and Larnu's comments.
No, you can't UPDATE a numeric column with text. You can, however, change the final presentation of the value.
Please note that the final result is a string and not a numeric value.
Example
Declare #YourTable table (SomeCol int)
Insert Into #YourTable values
(25)
,(null)
Select SomeCol = coalesce(left(SomeCol,10),'New Account')
From #YourTable
Returns
SomeCol
25
New Account

tSQL - convert nvarchar(8) to time only

I am using Microsoft SQL Server Management Studio to manipulate Public transport system database.
I have a table in database named 'dbo.tblStop_times', two columns of which should be of data type time. At the moment, they are both nvarchar and they have data stored in a pattern like this - "07:39:00" (without quotes)
I had same question with date columns as well, but found a solution for that on stackoverflow just few hours back.
Below works fine for conversion of nvarchar column to date column.
ALTER TABLE tblCalendar ALTER COLUMN [start_date] DATE NOT NULL;
I am not sure if what I want is achievable or not, because the above mention conversion works just fine, I assume it might be possible.
What I have atm is - nvarchar(8), what I want it to be is sql time data type, something like hh:mm:ss [and if possible - without trailing nnnnnn - nanoseconds component]
You should be able to do:
ALTER TABLE tblStop_times ALTER COLUMN start_time TIME NOT NULL;
Here is a rextester.
EDIT:
If you don't have valid time values, then you have a problem. You should first look for the values:
select col
from tblStop_times
where try_convert(time, col) is null;
This will show you the values that cannot be converted. If you like, you can NULL them out so the alter will work:
update tblStop_times
set col = NULL
where try_convert(time, col) is null;

How to convert date in mm/dd/yyyy format to yyyy-mm-dd hh:mi:ss.mmm

I'm inserting data into a table and before inserting I need to check if data exists.
I have a composite key consisted of two columns of datetime and int.
Before inserting I need to check if the data with the same time and id exists in the table.
The date that user is inserting is in 'mm/dd/yyyy'.
The datetime data in the table looks like this: '2016-01-12 00:00:00.000'.
The id field is int.
So, I have a query:
if not exists(select count(*) from table_1 where MyDate = #myDate and id = #id)
insert into table_1 .....
What is the right way to format the date user sends to match the datetime format in the table?
Check this sqlfiddle about how to use different date formats in your query. Might help you to solve it.
http://www.sqlfiddle.com/#!2/fd0b7/5
I am guessing that the question is about SQL Server, based on the syntax. The issues in the code snippet far transcend date formats.
First, the expression:
if not exists(select count(*) from table_1 where MyDate = #myDate and id = #id)
will never return true, because the subquery always returns one row with one column. If nothing matches, the column contains 0, which does exist.
You intend:
if not exists(select 1 from table_1 where MyDate = #myDate and id = #id)
Second, this check is not necessary if you wisely choose to have the database enforce the uniqueness constraint. So, define a unique index or constraint on the two columns:
create unique index unq_table_1_id_mydate on table_1(id, MyDate);
Now, the database won't let you insert duplicate values and no if is necessary.
Next, I would suggest that you fix the date format at the application layer. YYYY-MM-DD is an ISO standard date format and quite reasonable. However, if you don't want to do that, use convert():
insert into table_1(id, MyDate, .....)
select #id, convert(datetime, #MyDate, 101), . . .
The value in the database looks to be correct stored as a date/time value, so this should work fine.
You can use following line to convert date to required format in SQL server:
select FORMAT(#your_date, 'yyyy-MM-dd HH:mm:ss', 'en-US') from Your_Table

Reg: Auto incrementing a value in SQL Table

I got a value in a field called it (EmployeeDetailKey - varchar(10)) with sequential values such as
00001, 00002, 00003....
It is in a table Employeedetail. When ever a new Employee detail has to be inserted I have to get the max(EmployeeDetailKey) and increment by 1 and store it back. If I have 10 employeedetail records that need to be inserted then the same procedure has to follow.
If the max(EmployeeDetailKey) = 00003 then after inserting 10 records
it has to be 00013. Later on after inserting let us say 100 records it has to
be 00113.
How can I do it in the form of MS-SQL statement.
Please note the column cannot be identity type.
Just add an identity column to your table. I would suggest something like:
IntEmployeeDetailKey int not null identity(1, 1) primary key,
. . .
Then add a computed column:
EmployeeDetailKey as (right(('00000' + cast(IntEmployeeDetailKey as varchar(10)), 5)
Then SQL Server will do the incrementing automatically. And you can get the value out as a zero-padded string.
If you prefer a solution without changing the table structure, then:
Cast your zero-padded string value to int. This is easy in SQl server, as it will easily convert such strings to numbers:
SELECT CAST('00003' AS int)
This will return integer value of 3.
Find MAX()
Just perform MAX() on column you've just converted to string, like...
SELECT MAX(CAST(mycolumn AS int)) FROM mytable
Actually, you don't have to do a conversion, as SQL server will sort the values correctly in original string representation.
Increment
This is easy, since you now have the integer value, so...
SELECT MAX(CAST(mycolumn AS int)) + 1 FROM mytable
Convert it back to zero-padded string
SQL Server 2008 is a bit tricky to tame here, since left-padding is not his speciality. However, starting from in SQL Server 2012, there is a FORMAT function available, so, you can use...
SELECT FORMAT(MAX(CAST(mycolumn AS int)) + 1, '00000') FROM mytable
If you have only SQL Server 2005 or 2008 available, you can use REPLICATE() combined with LEN() to get what you need (disclaimer: UGLY CODE):
SELECT REPLICATE('0', 5 - LEN(MAX(CAST(mycolumn AS int)) + 1)) + CAST((MAX(CAST(mycolumn AS int)) + 1) AS nvarchar(5)) FROM mytable
EDIT As Luaan hinted, you can use another padding option (shorter and more readable code):
SELECT RIGHT('00000' + CAST(MAX(CAST(mycolumn AS int) + 1) as nvarchar(5)), 5) FROM mytable
I don't know if it is mandatory that EmployeeDetailKey must have this format.
I'll suggest you to substitute the datatype from varchar(10) to IDENTITY.
IDENTITY is a sort of special data type that gets automatically incremented by SQL Server each time you insert a row in the parent table. You can learn more here: https://msdn.microsoft.com/en-us/library/ms186775.aspx
If you need to present it with leading zeroes you can always select it like this (liberally adapted from here: Most efficient T-SQL way to pad a varchar on the left to a certain length?):
SELECT right('00000'+ rtrim(EmployeeDetailKey), 5) FROM YourTable

Converting datetime to short date from a declared table in sql

This is my first question on StackOverflow so I apologize for this most likely being formatted incorrectly. I am very new to sql language and am having trouble with the following query:
I have a declared table with one row selecting for a datetime (OccurrenceGroupID) and would like to have that date show up with short date formatting in the query results.
--Select for Occurrence Group
Declare #A3 table (OccurrenceGroupID datetime)
insert into #A3
select OccurrenceGroup as OccurrenceGroup,
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
from tblOccurrenceGroup
where occurrencegroupid = #occurrencegroupid
I get the error message "Column name or number of supplied values does not match table definition."
Any help would be much appreciated.
Thanks.
Your error is because you are selecting two columns and trying to insert the result set into a table with only one column.
Regardless of this you are converting a datetime to a varchar presumably for presentation reasons and then wanting to insert it into a column of type datetime which doesn't make much sense. Always leave the formatting of dates to the client application.
you have declared it as datetime
Declare #A3 table (OccurrenceGroupID datetime)
so it expects a date and a time you the go on to say
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
you then say convert the varchar as MM/DD/YYYY therefor it is contradictory to your first statement