T-SQL Conversion failed when converting the nvarchar value '12-02' to data type int - tsql

I'm trying to convert this NVARCHAR value into a periodeId.
The Raw data could be '12-02'.
My solution for this was first to try this
(1000+CONVERT(INT,LEFT(2,T1.PERIOD_NAME)))*100+CONVERT(Int,RIGHT(2,t1.PERIOD_NAME))
But i get the same error message here and could find any quick solution for it.
I also tried to just do a simple
LEFT(2,T1.PERIOD_NAME) to see if it was the formula itself that crashed it, but the same error came up.

If you want '12-02' to be 1202, then use replace() to remove the hyphen before conversion:
select cast(replace(period_name, '-', '') as int)
In SQL Server 2012+, you should use try_convert(), in case there are other unexpected values.

You can try:
SELECT (1000+CONVERT(INT,LEFT(t1.PERIOD_NAME,2)))*100+CONVERT(Int,RIGHT(t1.PERIOD_NAME,2))
The character_expression that LEFT operates on is at first place, whereas the integer expression that specifies how many characters of the character_expression will be returned, comes at second place.

Related

Why single quote escape cannot be used in QuestDB, Error: dangling expression

I'm trying to use Query Variables in Grafana, the panel query source is PostgreSQL for QuestDB.
I have added the variable without any issue, but I'm unable to use the variable in Panel query since the variable values contains the spaces (SENSOR01 ON_OFF), also I'm unable to figure-out how to add single quote escape.
Following are the scenarios I tried:
Scenario1: this indicates due to space in the Variable value, on_off considered as separate word
where sensor_name = $sensor
db query error: pq: unexpected token: on_off
.
.
Scenario2: tried to add single quotes explicitly for the variable value, but there is generic error from source DB (QuestDB)
where sensor_name = concat('''', $sensor, '''')
db query error: pq: dangling expression
When tried Scenario2 approach directly in query of Variable, getting the same error
..
Scenario3: Hard-coded the variable value with space and with single quotes, but this giving me error with first part of the variable, looks like the hard-coded single quotes not passed here!
Error (Scenario3):
Is there any way/workaround to tackle this issue?
Could you just add the quotes directly in the query?
where sensor_name = '$sensor'
I have a similar grafana panel querying a questDB database using a variable and it works for me. This is my query:
select device_type, avg(duration_ms) as avg_duration_ms, avg(speed) as avg_speed, avg(measure1) as avg_m1, avg(measure2) as avg_m2 from ilp_test
WHERE
$__timeFilter(timestamp) and device_type = '$deviceType'
A rather hacky workaround would be to do:
where sensor_name = concat(cast(cast('&' as int) + 1 as char), $sensor, cast(cast('&' as int) + 1 as char))
This should work, but I'm pretty sure there is a better solution. Let me find it and get back to you.
Update. We may support Postgres syntax (which is '' escaping for a single quote char) in one of upcoming versions. For now, you'd have to use the above workaround.

Postgres, query error: ERROR: operator does not exist: character varying = bigint?

I am trying to run this query:
select *
from my_table
where column_one=${myValue}
I get the following error in Datagrip:
[42883] ERROR: operator does not exist: character varying = bigint Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Now, I have found this question, and I can fix the error by putting a string like this:
select *
from my_table
where column_one='123'
What I need is a way to pass in the '123' as a parameter. I usually do this ${myValue} and it works, but I am not sure how to keep my variable there as an input so I can run dynamic queries in code and let Postgres understand I want to pass in a string and not a number.
Any suggestions?
Here's a screenshot of how I am putting the parameter value in DataGrip...:
Ok, so, I just tried to put quotes in the data grip parameters input field for myValue #thirumal's answer things work. I didn't know I have to quote the value for it to work.
This is what it looks like:
Type cast ${myValue} using SQL Standard,
cast(${myValue} AS varchar)
or using Postgres Syntax:
${myValue}::varchar

PostgreSQL: how to extract value attribute from XML

I am trying to convert the following SQL Server query to Postgresql
select CAST(CAST('<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>' as XML).value('(//StartTime/#value)[1]', 'datetime') AS varchar(40)) + ''')';
I have tried converting it to below and got back following error.
select unnest(xpath('//StartTime/#value', xmlparse(document '<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>')))
Error:
ERROR: invalid XML document
DETAIL: line 1: Extra content at the end of the document
<IncludeSettle/><StartTime value="2010-03-26 08:45:48.780"></StartTim
^
SQL state: 2200M
As a hack, I had made the following change to make it work.
select unnest(xpath('//StartTime/#value', xmlparse(document '<tempzz>'||'<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>'||'</tempzz>')))
Output for Postgresql:
2019-03-26 08:45:48.780
I am looking for a better solution. Any help really appreciated.
You can process that by adding the dummy root as you did. The value is already formatted as an ISO timestamp, so you can simply cast it to a timestamp:
But as there is no direct cast from xml to timestamp you need to cast the result of the xpath() to text first.
with data (input) as (
values ('<IncludeSettle/><StartTime value="2019-03-26 08:45:48.780"></StartTime>')
)
select (xpath('//StartTime/#value', ('<dummy_root>'||input||'</dummy_root>')::xml))[1]::text::timestamp
from data

Display blank value ("") as date in SSRS

I have the column DiscontinuedDate with either a datetime or a blank value. I used the expression
FormatDateTime(Fields!DiscontinuedDate.Value, DateFormat.ShortDate)
To show the date time as just a date but then when the value is blank it shows as an error with the following message "Conversion from string "" to type 'Date' is not valid."
So i've been trying to use an IIF expression like the below:
=IIF(Fields!DiscontinuedDate.Value is "", "", FormatDateTime(Fields!DiscontinuedDate.Value, DateFormat.ShortDate))
I've tried a few variations but they all bring back the same error. Any ideas?
Thanks,
Adam
Your issue is that SSRS IIf expressions do not short circuit, so whenever you have a blank string your code will still be trying the FormatDateTime conversion, so you get this error even with your check.
You can add some logic to stop the empty string being evaluated in the FormatDateTime expression by using another IIf to change it to a NULL value, which won't fail:
=IIF(Fields!DiscontinuedDate.Value = ""
, ""
, FormatDateTime(IIf(Fields!DiscontinuedDate.Value = ""
, Nothing
, Fields!DiscontinuedDate.Value)
, DateFormat.ShortDate))
That solves your immediate issue, but assuming the underlying data is text based, I would also recommend looking at your underlying data and using explicit DateTime type data types instead of strings to prevent these at the lowest possible level.

sqlite issue using WHERE statement on a varchar field in Objective-C

I have this sql statement SELECT * FROM Language WHERE LanguageCode=? where LanguageCode is a varchar(2).
When I use sqlite3-prepare-v2 on that statement I got SQLITE_ERROR but if I use SELECT * FROM Language WHERE LanguageID=? where LanguageID is the primary key numeric identity field the statement compiles just fine.
Is there any issue filtering by a varchar field using WHERE statement?
Thanks
I think there should be no issue with the where statement by using a varchar field.
Maybe you are having problem with passing the parameter. Try to print to NSLog and see the statement that is executed, and execute it with the sqlite command prompt to see if you have return values.
Be sure your ? is wrapped in single quotes.
SQLite should also give you an error string which tell you why there is an error.
Try to call sqlite3_errmsg and check the error string returned from that call. It should give you a more detailed information about what went wrong.
Claus