Could anyone help me understand why the following query works fine in SQL 2000 and not in SQL 2005
In SQL 2005 it errors out "The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value"
DECLARE #Table table(date varchar(6),code char(1))
INSERT INTO #Table select '010209','N'
INSERT INTO #Table select '032809','N'
INSERT INTO #Table select space(6),'N'
select * FROM #Table
WHERE
(
(
date <> ''
AND
GETDATE() < CAST(LEFT(date, 2) + '/' + SUBSTRING(date, 3, 2) + '/' + RIGHT(date,2) AS SMALLDATETIME)
)
OR code = 'Y')
Yes, leppie could have been a bit clearer, but <> '' does not match your space(6).
This will work (using ltrim/rtrim)
DECLARE #Table table(date varchar(6),code char(1))
INSERT INTO #Table select '010209','N'
INSERT INTO #Table select '032809','N'
INSERT INTO #Table select space(6),'N'
select * FROM #Table
WHERE
(
(
ltrim(rtrim(date)) <> ''
AND
GETDATE() < CAST(LEFT(date, 2) + '/' + SUBSTRING(date, 3, 2) + '/' + RIGHT(date,2) AS SMALLDATETIME)
)
OR code = 'Y')
The error is exactly what it says.
No matter how hard you try, ' / / ' will never ever be any date.
Use
date.RTRIM() <> ''
instead of
date <> ''
Related
CREATE FUNCTION dbo.KeyValuePairs( #inputStr VARCHAR(MAX))
RETURNS #OutTable TABLE
(KeyName VARCHAR(MAX), KeyValue VARCHAR(MAX))
AS
BEGIN
DECLARE #separator CHAR(1), #keyValueSeperator CHAR(1)
SET #separator = ','
SET #keyValueSeperator = ':'
DECLARE #separator_position INT , #keyValueSeperatorPosition INT
DECLARE #match VARCHAR(MAX)
SET #inputStr = #inputStr + #separator
WHILE PATINDEX('%' + #separator + '%' , #inputStr) <> 0
BEGIN
SELECT #separator_position = PATINDEX('%' + #separator + '%' , #inputStr)
SELECT #match = LEFT(#inputStr, #separator_position - 1)
IF #match <> ''
BEGIN
SELECT #keyValueSeperatorPosition = PATINDEX('%' + #keyValueSeperator + '%' , #match)
IF #keyValueSeperatorPosition <> -1
BEGIN
INSERT #OutTable
VALUES (LEFT(#match,#keyValueSeperatorPosition -1),
RIGHT(#match,LEN(#match) - #keyValueSeperatorPosition))
END
END
SELECT #inputStr = STUFF(#inputStr, 1, #separator_position, '')
END
RETURN
END
GO
when input is '1:10,2:20'
This gives the output as string parse
KeyName KeyValue
1 10
2 20
I need additional logic on top of it: I will send
'Stadium','1:10,2:20' as input to a function then
output should be
StadiumA StadiumB
10 20
i.e: in 1:10,2:20' key 1 refers to A AND append 'Stadium' to it .
key 2 refers to B and append 'Stadium' to it an so on continues
I have tried joining with below
ALTER FUNCTION [dbo].[ParseDeviceTopology](#Type NVARCHAR(255),#Value NVARCHAR(MAX))
RETURNS #Parsed TABLE (Topology NVARCHAR(50),Value NVARCHAR(50))
AS
BEGIN
INSERT INTO #Parsed(Topology,Value)
SELECT #Type + m.Topology + 'Version' AS Topology,p.[1] AS [Value]
FROM (
SELECT j.[key] AS [ID],i.[key],i.value
FROM OPENJSON('["' + REPLACE(#Value,',','","') + '"]') j
-- CROSS APPLY OPENJSON('[' + REPLACE(j.[value],':',',') + ']') i
CROSS APPLY OPENJSON('["' + REPLACE(j.[value],':','","') + '"]') i
) a
PIVOT(MAX(a.value) FOR a.[key] IN ([0],[1])) p
INNER JOIN ( VALUES` ` INNER JOIN ( VALUES
(2,'B')
,(1,'A')
,(3,'C')
)` `m(ID, Topology) ON m.ID = p.[0];
But I was getting the output as required in my local machine 2016 SQL but this logic uses OPENJSON which is incompatible in SQL 2014 where I need to deploy. Please help me out
I honestly wouldn't do this in SQL, instead, parse the key value pairs into an object in your external code.
If you absolutely have to do this in SQL I would suggest looking at using a CLR string splitter function as detailed here https://sqlperformance.com/2012/07/t-sql-queries/split-strings
In your case you would need an initial pass to split by comma to return a single column of tabular data, then a pass of that column to split by the semi colon.
I have a SQL Server columns with data like this:
formula amount ficheno
-----------------------------
100*444 100 6555
10*698 698 6555
I've already tried on SQL Server converted varchar to double getting error.
Need to get formula field to resulted field...
You can evaluate an expression using dynamic SQL:
declare #sql nvarchar(max) = (
select string_agg(cast(
'select ' + formula + ', ' + str(amount) + ', ' + str(ficheno)
as nvarchar(max)), ';')
from YourTable
);
declare #temp table (id int, amount int, ficheno int);
insert #temp exec(#sql);
select * from #temp;
-->
id amount ficheno
44400 100 6555
6980 698 6555
Working example at db<>fiddle.
Ive followed your query and succeed Thank you so much #Andomar. Reviewed code to work on sql server<2017 with stuff function. If anyone is looking for answer ;
declare #sql nvarchar(max) = (
SELECT STUFF( (SELECT ' select ' + str([LOGICALREF]) + ', ' + str([LOGICALREFI]) + ', ' + REPLACE( Formül,',','.') +';'
from BM_211_URETIM_PLANLANAN t
for xml path ('')
), 1, 1, '' )
)
declare #temp table ( [LOGICALREF] int, [LOGICALREFI] int, [Planlanan Miktar] FLOAT);
insert #temp exec(#sql);
How can I get 2nd column format in SQL Server 2008?
For example:
SELECT
GETDATE() col1,
'16-09-2017 11:20 AM' col2
select convert(varchar(10),GETDATE(), 105) + right(convert(varchar(32),GETDATE(),100),8)
A handy snippet for such an occasion:
DECLARE #i INTEGER = 0
WHILE #i < 255
BEGIN
SELECT #i += 1
Declare #out Table (zample varchar(max), aline varchar(max))
BEGIN TRY
insert into #out(zample, aline)
SELECT CAST(n AS VARCHAR(MAX)) + ' - ' + CONVERT(VARCHAR(MAX), GETDATE(), n) xZample, 'CONVERT(VARCHAR(MAX),#MindIfWeDanceWitYoDates, ' + CAST(n AS VARCHAR(25)) + ')' AS _________________________tehcode____________________________
FROM (SELECT #i AS n) x
END TRY
BEGIN CATCH
--do nothing
exec(';');
END CATCH
END
select * from #out
How to combine rows in SQL Server 2000
Have you tried using FOR XML RAW in SQL Server 2000?
You can create a user defined function to perform the string concatenation for each ID value.
create table t (id int,start varchar(100),finish varchar(100))
insert into t
select 1,'Start_Main', '' union all
select 1,'Start_Submain1', '' union all
select 2,'Start_Main', '' union all
select 2,'Start_Submain2', 'End_Submain2' union all
select 2,'Start_Submain3', 'End_Submain3' union all
select 2,'Start_Submain1', '' union all
select 2,'Start_Submain4', 'End_Submain4'
Select * from t
go
/* User Defined Function to perform string concatenation per ID */
create function udfStringConcat (#ID int)
returns varchar(500)
as
begin
declare #x varchar(500)
set #x = ''
select #x = #x + t.start + ',' + case when t.finish <> '' then t.finish + ',' else t.finish end
from t
where t.id = #ID
select #x = #x + 'End_Submain1,End_Main'
return #x
end
go
select id, dbo.udfStringConcat(id)
from t
group by id
go
drop function udfStringConcat
drop table t
go
Using SQL Server 2005
Date Time
20060701 090000
20060702 020000
20060703 180000
...
Date and Time datatype is varchar
Tried Query
select Convert(datetime, Convert(char(10), date, 103) + ' ' + Convert(char(8), time, 108), 103) from table
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, date)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, time), time)
as datetime) from table
It showing error as out of range value.
How to solve this issue.
Need Sql Query Help
First off, why are you storing a DATETIME in a VARCHAR?
This should be able to help
DECLARE #Table TABLE(
Val VARCHAR(20)
)
INSERT INTO #Table (Val) SELECT '20060701 090102'
INSERT INTO #Table (Val) SELECT '20060702 020000'
INSERT INTO #Table (Val) SELECT '20060703 180000'
SELECT *,
CAST(SUBSTRING(Val,1,8) + ' ' + SUBSTRING(Val,10,2) + ':' + SUBSTRING(Val,12,2) + ':' + SUBSTRING(Val,14,2) AS DATETIME)
FROM #Table
I came across a similar issue a few years ago, when importing HL7 messages. Here is a copy of the function I used. It creates a DateTime string with the time component correctly separated into hh:mm:ss, which is needed for the cast to DateTime.
CREATE FUNCTION fn_StringDateTietoDateTime
(
#Date varchar(15)
)
RETURNS datetime
AS
BEGIN
DECLARE #Result DATETIME
SET #Result = NULL
If len(#Date) > 0
BEGIN
SELECT #Result = CAST(SUBSTRING(#hl7date, 1, 8) + ' ' + SUBSTRING(#hl7date, 10, 2) + ':' +
SUBSTRING(#date, 12, 2) + ':' + SUBSTRING(#date,14, 2) AS DATETIME)
END
RETURN #RESULT
END