I would like to understand question about conversion:
exam dump I'm working with has this question at least three times with 3 different solutions you approve or don't approve of note that RegistrationNumber is defined as varchar(5) :
You run the following query:
SELECT UserId FROM tblVehicleRegistration
WHERE RegistrationNumber = 20012
AND RegistrationDate > '2016-01-01'
The query output window displays the following error message: “Conversion failed when converting the varchar value ‘AB012’ to data type int.”
You need to resolve the error.
Solution: You modify the Transact-SQL statement as follows:
SELECT UserId FROM tblVehicleRegistration
WHERE RegistrationNumber = '20012'
AND RegistrationDate > '2016-01-01'
answer says this does not work
I would think the test is incorrect. Here is a simplified example:
declare #tblVehicleRegistration table (RegistrationNumber varchar(5))
insert into #tblVehicleRegistration(RegistrationNumber) VALUES('AB012')
SELECT * FROM #tblVehicleRegistration WHERE RegistrationNumber = 20012 --Fails as expected
SELECT * FROM #tblVehicleRegistration WHERE RegistrationNumber = '20012' --works as expected
SQL Server will do a convertion in order to compare 'AB012' and 20012. If you check this link Data type precedence you will see that type varchar, wich is low precedence, needs to be converted to int, wich is high precedence, in order to make a comparison.
I created a table and tried hands-on. It worked properly after casting or changing the integer value to a string with quotation marks.
Related
I'm trying to use a query to get date type value but it doesn't work...
tables:
Create table Clients1(
login char(30) primary key,
password varchar(30),
date_ad date,
name_c varchar(30),
adress varchar(30),
card_c varchar(30)
);
Create table clients_pay(
payment_ID char(15) primary key,
login char(15)
);
The following error appears:
22P02: invalid input syntax for integer: "2019/12/02"
My query is as follows:
SELECT DISTINCT login, COUNT(payment_ID) AS p
FROM Clients1
NATURAL INNER JOIN Payments1
NATURAL INNER JOIN clients_pay
GROUP BY login
HAVING COUNT(payment_ID) >='2019/12/02';
Since it's type date why it appears as integer?
I'm trying to see which clients can use service at date 2019/12/02?
(They can if payed)
Thank you
It looks like you want to have a WHERE clause limiting the payment_ids returned by a date, such as:
SELECT login, COUNT(payment_ID) AS p
FROM clients1
INNER JOIN clients_pay
ON clients_pay.login = Clients1.login
WHERE date_ad >='2019/12/02'
GROUP BY login ;
I also made some assumptions about the intention of your query and your data model, please edit your question to clarify those things if this doesn't meet your needs. Also note, Postgres identifiers are coerced to lowercase by default, unless you specify the casing by putting double quotes around the identifier during object creation. That practice is highly discouraged, though.
I am trying to run a query that has a where clause with a string from a column of type VARCHAR(50) through PHP, yet for some reason it does not work in either PHP or MySQLWorkbench. My database looks like:
Database Picture:
The table title is 'paranoia' where the column 'codename' is VARCHAR(50) and 'target' is VARCHAR(50). The query I am trying to run takes the form, when searching for a codename entry clearly named '13Brownie' with no spaces, as follows:
UPDATE paranoia SET target='sd' WHERE codename='13Brownie'
Yet for some reason passing a string to the argument for codename is ineffective. The WHERE clause works when I do codename=7 or codename=3 and returns those respective integer codenames, and I can do codename=0 to get all the other lettered codenames. The string input works in neither MySQLWorkbench or the PHP script I will be using to update such selected rows, but again the integer input does.
It seems like the WHERE clause is only taking the integer values of my string input or the column is actually made up of the integer values of each entry, but the column codename is clearly defined as VARCHAR(50). I have been searching for hours but to no avail.
It is likely that there are white-space characters in the data. Things to try:
SELECT * FROM paranoia WHERE codename like '13%'
SELECT * FROM paranoia WHERE codename = '13Brownie '
SELECT codename, LEN(codename) FROM paranoia
VARCHAR(10) is a valid type to accept a string of at most 10 characters. I think this can possibly happen because of a foreign key constraint enforced with another table. check if you have this constraint using the "relation view" if you are on phpmyadmin.
I'm trying to pull data for certain dates out of a staging table where the offshore developers imported everything in the file, so I need to filter out the "non-data" rows and convert the remaining strings to datetime.
Which should be simple enough but... I keep getting this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I've taken the query and pulled it apart, made sure there are no invalid strings left and even tried a few different configurations of the query. Here's what I've got now:
SELECT *
FROM
(
select cdt = CAST(cmplt_date as DateTime), *
from stage_hist
WHERE cmplt_date NOT LIKE '(%'
AND ltrim(rtrim(cmplt_date)) NOT LIKE ''
AND cmplt_date NOT LIKE '--%'
) f
WHERE f.cdt BETWEEN '2017-09-01' AND '2017-10-01'
To make sure the conversion is working at least, I can run the inner query and the cast actually works for all rows. I get a valid data set for the rows and no errors, so the actual cast is working.
The BETWEEN statement must be throwing the error then, right? But I've casted both strings I use for that successfully, and even taken a value out of the table and did a test query using it which also works succesfully:
select 1
WHERE CAST(' 2017-09-26' as DateTime) BETWEEN '2017-09-01' AND '2017-10-01'
So if all the casts work individually, how come I'm getting an out-of-range error when running the real query?
I am guessing that this is due to the fact that in your cmplt_date field there are values which are not valid dates. Yes, I know you are filtering them using a WHERE clause, but know that Logical Processing Order of the SELECT statement is not always the actual order. What does this mean is that sometimes, the SQL Engine my start performing your CAST operation before finishing the filtering.
You are using SQL Server 2012, so you can just add TRY_CAST:
SELECT *
FROM
(
select cdt = TRY_CAST(cmplt_date as DateTime), *
from stage_hist
WHERE cmplt_date NOT LIKE '(%'
AND ltrim(rtrim(cmplt_date)) NOT LIKE ''
AND cmplt_date NOT LIKE '--%'
) f
WHERE f.cdt BETWEEN '2017-09-01' AND '2017-10-01'
I have a function in PL/pgSQL that is trying to back out some data for a date range. The problem I have is that I cannot seem to store the double precision inside a variable. No matter what I do the value is always null when running inside a function. When I run the query from psql command line it returns me the correct data. I can also run the query on another column that is isn't of type double precision and it works fine. For example if I change the column to "total_impressions_for_date_range" it will return me the correct data.
I am using PostgreSQL 8.4
CREATE OR REPLACE FUNCTION rollback_date_range_revenue(campaign_id int,
begin_date timestamp, end_date timestamp, autocommit boolean)
RETURNS void AS $BODY$
DECLARE
total_impressions_for_date_range bigint;
total_clicks_for_date_range bigint;
total_revenue_for_date_range double precision;
total_cost_for_date_range double precision;
BEGIN
SELECT sum(revenue) INTO total_revenue_for_date_range
FROM ad_block_summary_hourly
WHERE ad_run_id IN (
SELECT ad_run_id FROM ad_run WHERE ad_campaign_id = campaign_id)
AND ad_summary_time >= begin_date
AND ad_summary_time < end_date
AND (revenue IS NOT NULL);
RAISE NOTICE 'Total revenue for given date range and campaign % was %',
campaign_id, total_revenue_for_date_range;
When I run this I always get a null value for the revenue
SELECT rollback_date_range_revenue(8818, '2015-07-20 18:00:00'::timestamp,
'2015-07-20 20:00:00'::timestamp, false);
NOTICE: Total revenue for given date range and campaign 8818 was <NULL>
When I run it from command line outside of the function it works completely fine
select sum(revenue) from ad_block_summary_hourly where ad_run_id in (
select ad_run_id from ad_run where ad_campaign_id = 8818) and ad_summary_time
>= '2015-07-20 18:00:00'::TIMESTAMP and ad_summary_time < '2015-07-20
20:00:00'::TIMESTAMP ;
sum
----------
3122.533
(1 row)
EDIT
Huge thanks to a_horse_with_no_name and Patrick. This was indeed a problem with a place holder I had called revenue which overlapped with my query. I was thrown off by the fact that the two queries that were not working were both double precision. It just happened to be that those two were also the place holders that I had overlapped with column names.
2 things to take away from this.
I adopted the p_ naming scheme for place holders suggested by a_horse_with_no_name, so as to not run into this issue again.
Post a full code example, this could have been identified much quicker by the experts.
First of all, PostgreSQL 8.4 is no longer supported so you should upgrade to 9.4 as soon as you can. Second, your function is obviously abbreviated because some declared variables are not used and there is no END clause. These two points together make it somewhat guesswork to give you an answer, but here goes.
Try casting the double precision to text, or convert it with to_char(). RAISE NOTICE expects a string for the expressions to be inserted; possibly in 8.4 this is not automatic.
You could also improve upon your query:
...
SELECT sum(sh.revenue) INTO total_revenue_for_date_range
FROM ad_block_summary_hourly sh
JOIN ad_run r USING (ad_run_id)
WHERE r.ad_campaign_id = campaign_id
AND sh.ad_summary_time BETWEEN begin_date AND end_date;
RAISE NOTICE 'Total revenue for given date range and campaign % was %',
campaign_id, to_char(total_revenue_for_date_range, '9D999');
...
Another potential cause of the problem (guessing again due to lack of information) is a name collision between a function parameter or variable with a column name from either of the two tables.
I recently, approx 2 months ago, needed to check for any field in a table that has NULL value.
I am now onto another task but this time i need to check if any field in a table has an Empty String value.
Starting Query:
;With xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
SELECT *
FROM [Schema].[Table] act
where (
select act.*
for xml path('row'), elements xsinil, type
).exist('//*/#ns:nil') = 1
I know i need to change #ns:nil but as i am uneducated on TSql's XQuery implementation, i need someone to help me with this initial query. As well, where i should go outside of MSDN to get read up on usage and functionality.
Update #1:
;With xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
Select *
from Schema.Table act
where (
select act.*
for xml path('row'), elements xsinil, type
).value('(//row/*)[1]', 'varchar(max)') = ''
Tried this but evidently one of the fields contains character 0x001C and so requires a conversion to binary, varbinary, or image and then use BINARY BASE64 directive.
Build the XML and check for node values that are empty. Simpler than checking for null and as stated in comment, only (n)varchar produces an empty string as a node value.
select *
from T
where (
select T.*
for xml path(''), type
).exist('*/text()[. = ""]') = 1