MS-Access - why can't this update query fill empty cells? - sql

In MS-Access database, table called NewTable3
colname is a text column containing lot of empty cells or blanks.
i want to put ? character in empty cells . when i run the query
UPDATE NewTable3 SET colname = '?' WHERE ISNULL(colname) ;
This query updates 0 records why . what is wrong with this query

Two quick things:
1) Try putting the colname in square brackets.
2) Remember that empty cells (Nulls) and empty strings ("") are different.
Together:
UPDATE NewTable3 SET [colname] = "?" WHERE ISNULL([colname]) OR [colname] = "";
Also, are you running the query in Access itself, or just using the Access engine and using the data in another program/via a VBA script? It can make a difference.

EDIT:
Based on #onedaywhen's prodding, I now see that I never fully absorbed the original question, which was asking about replacing Nulls with the literal ? character. This is insane and not helpful or useful. If you don't have a meaningful default value for the field, then LEAVE IT NULL. If you want to distinguish between Null (unknown) and Blank (i.e., known to be blank), you can allow zero-length strings and change the Nulls to ZLS.
My original post follows, since I think it is useful for people who might get to this crazy question needing to do things properly:
In total, all the answers in this thread end up solving all the problems with the original SQL statement, but they do so incompletely, so I'll compile them all together in an attempt to create a comprehensive correct answer.
#Wim Hollebrandse wisely points out that a parameter needs brackets, but posts the SQL as:
UPDATE NewTable3 SET colname = '[?]' WHERE ISNULL(colname);
This is incorrect, in that the quotes will cause what's inside them to be treated literally, instead of evaluated as a paramter, so you'll end up with all your fields updated to the literal value "[?]". The correct syntax would be:
UPDATE NewTable3 SET colname = [?] WHERE ISNULL(colname);
#GuinnessFan points out a problem in the WHERE clause, suggesting out that the result of IsNull() needs to be compared to True in order for the WHERE clause to work. In other words, this:
WHERE IsNull(NewTable3.colname)
...should be this:
WHERE IsNull(NewTable3.colname)=True
But given that both statements evaluate the same, they are entirely equivalent. But #GuinnessFan is correct that this is the best syntax:
WHERE NewTable3.colname Is Null
#mavnn points out that the fields may be "empty" while not being Null, which is a very common problem. I believe on principle (and consistent with my understanding of the official SQL standards) that fields should be initialized as Null and should not allow zero-length strings. It is certainly possible in some applications that one might want to distinguish Null, i.e., value not yet supplied, from blank (zero-length string), i.e., value known to be blank. But if that's part of the application design, then the user should know that criteria on such fields need to consider whether one or both should be included (i.e., both Null and <>"" or one or the other).
From my point of view, it was unfortunate that the the old default for text fields (where AllowZLS defaulted to FALSE) was changed in Access 2003 to allow ZLS's by default. This means that many people who don't notice that AllowZLS is set to TRUE when they create their tables end up with ZLS's stored in their text fields without intending to do so (and importing a table from a previous version also defaults to TRUE).
While testing for Null and ="" will make the WHERE clause that is seeking all "empty" fields work as expected, the permanent fix is to change the field definition to disallow ZLS's. But do note that changing AllowZLS to FALSE does not clear the existing ZLS's -- you have to run a SQL UPDATE to remove them.
Last of all, in using parameters, it is better to declare them such that the values that the user can input are restricted to appropriate values. If the field is numeric, you to limit it to numeric values, if a date, date values, if text or memo, to text:
PARAMETERS [User Prompt] Long;
UPDATE MyTable SET LongIntegerColumn = [User Prompt]
PARAMETERS [User Prompt] DateTime;
UPDATE MyTable SET DateColumn = [User Prompt]
PARAMETERS [User Prompt] Text ( 255 );
UPDATE MyTable SET TextColumn = [User Prompt]
Note that with Text(255) as your parameter type, anything supplied by the user is truncated to 255 characters, even if it's longer than that (it would be a pretty unusual situation where'd you'd need that). For values longer than that (such as memo fields), you omit the text length declaration:
PARAMETERS [User Prompt] Text;
UPDATE MyTable SET TextColumn = [User Prompt]
In any event, I think so-called anonymous parameters are not too helpful, as you aren't leveraging the power of parameters to restrict data type of input criteria.

Try:
UPDATE NewTable3 SET colname = '[?]' WHERE ISNULL(colname);
The questionmark is used for anonymous parameters, so you need to escape it as above. Note that I have not tried this.

UPDATE NewTable3 SET NewTable3.colname = "?"
WHERE (((NewTable3.colname) Is Null));
To keep your function: WHERE (((IsNull([NewTable3.colname]))=True));

I don't believe that replacing the NULL value with your own 'magic' value ? will cause you anything but further pain.
Here's hoping you may draw inspiration from this article:
How To Handle Missing Information Without Using (some magic value)

Related

SQL string comparison -how to ignore blank spaces

I have prepared an SQL query that I will have to run on several databases (Oracle and Sybase) where some data might be stored differently.
I have noticed that one of the differences in data storage is the blank string.
For example, in the column PRODUCT_TYPE below, please have a look at the second record:
This "empty string" (the data type is CHAR(15)) circled in red is equal to '' in some of the databases, whereas it's equal to ' ' to some others. The length is never constant and there are several fields that behave as such.
So, since I need to filter on these "empty strings", I should change the following statement in my WHERE clause:
WHERE PRODUCT_TYPE = ''
...because the above will take the ' ' string as different than '' even if "functionally" speaking is not.
I would hence like to make the statement in a way that it "ignores white spaces", i.e. ' ' is equal to '' that is equal to ' ' etc.
How should I do this change in order to make it work?
I have tried the simple replacing approach:
WHERE REPLACE(PRODUCT_TYPE,' ','') = ''
...but it doesn't seem to work, probably because I should use a different character.
For sake of testing, inside the ' below there is a copied-pasted example of what I find in these "empty strings":
' '
Ideally, it should be a "non-specific SQL" solution since I will have to run the same query on both Oracle and Sybase RDBMS. Any idea?
You can use trim on the column.
where trim(product_type) is null
The above is not DBMS-independent, since Sybase does not provide the trim function.
However, the below approach will work both in Sybase and Oracle:
where rtrim(ltrim(product_type)) is null
You can use the replace statement you've tried but you should test for "is null" instead of =''
WHERE REPLACE(PRODUCT_TYPE,' ','') is null
See also:
null vs empty string in Oracle
The simple (and non-DBMS specific) answer is:
Do not use CHAR(15).
char(n) is a fixed length data type. So no matter what you store in there, the value will always be padded to the defined length. If you store a single character, the DBMS will store that single character and 14 spaces.
Change your columns to use varchar(15) and you should not have any problems.

Escaping special characters when naming a table column without setting define off

Before I posted my question, I read up various posts on this site about how to escape a special character when inserting a new field value or looking for a field name in the where clause. What I did not find was how to escape a special character when you want to name a table or column with one.
So, I want to name fieldA as this&that, e.g.
select fieldA this&that from tableA
I also want to use a substitution variable (&var) in the same query, so set define off wouldn't help.
I tried to use 'this' || chr(38) || 'that' with or without single quotes, but SQL Developer doesn't like either.
Any ideas?
You would need to quote the identifier, but this is a really bad idea; every reference to the column everywhere will also have to be quoted and match the case exactly. See this, and the documentation, which advises against using quoted identifiers.
It's an even worse idea with an ampersand because of its use for substitution variables, as you're seeing. To create the table and then use substitution variables in the same script you would need to turn off defines before the creation, and then turn them back on afterwards:
set define off
create table bad_idea("this&that" number);
set define on
But you still couldn't refer to the table name and a substitution variable in the same statement, unless you set define to something non-standard:
set define "^"
insert into bad_idea("this&that") values (^var);
But again everything that ever refers to that column will need to take that into account too, as well as the case and quoting.
I'd seriously reconsider and make it something like this_and_that, or omit the 'and' part completely if it isn't really adding anything (or your real column name is approaching the length limit).
If you only need it as a column alias you can do the same thing, and it would be slightly less painful, but still not ideal:
set define "^"
select fieldA "this&that" from tableA where fieldB = ^var;

Insert zero before a numeric datatype in SQL Server

I was trying insert a value in a column in SQL Server which is of type numeric(18, 0).
I am unable to insert a zero at the beginning. For example adding 022223 gets inserted as 22223...
I think changing the column type to varchar will work but I don't want to alter table structure.
Any way to do this without changing the table structure..Please help
There is no point to have this IN a database. You will, afterall, select the data, won't you? So while selecting do something like this. I looked in google for "mssql numeeric leading zeros". All of the solutions are like in the link I have mentioned :) Or obviously, use varchar if you, for some reason, must have data like that in a table :)
you can apply a transformation when reading and inserting the value like this:
when inserting value :
string s = "00056";
double val = double.Parse("0." + s);
and when querying value use:
double value = 0.00056; // stored value in your db field
s = val.ToString().Remove(0,2);
i think it will work in any case - whether you have leading zero in your value or not.
Well I dont think it's possible, since its being stored as a 32 bit so simply add leading zeros when printing it ...
There are multiple approaches.
http://sqlusa.com/bestpractices2005/padleadingzeros/

How to prepend(?) number in text field with '0'?

I have a text field in Microsoft Access which consists of only digits. I don't know if these digits are preceded by blank characters or not.
What I want to do is if the field has '1' I want to convert it to '0001', if it has '89' then I want to convert it to '0089', etc. Meaning I just want to make the field consistent in length of 4 characters and pad the number with the appropriate number of '0's.
How do I do this? Can I use the calculated field approach?
I can convert the database to SQL if SQL has an easy way to do this.
Thanks.
You can use the Format() function to transform the string of digits. Format() doesn't care whether or not the digits are preceded by spaces.
? Format("89","0000")
0089
? Format(" 89","0000")
0089
If you want to display those field values with that format in a query:
SELECT Format([YourTextField],"0000")
FROM YourTable;
If you want to change how they're stored:
UPDATE YourTable
SET [YourTextField] = Format([YourTextField],"0000");
Edit: #onedaywhen suggested a using CHECK CONSTAINT or Validation Rule to ensure your table only accepts valid data in the future. Here is a CHECK CONSTRAINT example:
ALTER TABLE YourTable
ADD CONSTRAINT four_digits_required
CHECK (
YourTextField LIKE '[0-9][0-9][0-9][0-9]'
);
You can run that statement from CurrentProject.Connection.Execute, which is an ADO object method. DDL statements with CHECK constraints can only be executed from ADO. So you could not execute that statement from CurrentDb.Execute, which is a DAO object method.
Alternatively this should work for YourTextField's Validation Rule property:
LIKE "[0-9][0-9][0-9][0-9]"
The Validation Rule approach would also allow you to use the Validation Text property to display a message to the user when submitted values are unacceptable:
"4 digits required."
In this situation the Validation Text approach is about the same as displaying the CHECK constraint name when that constraint is violated. However, if you wanted a more detailed message, the Validation Text could be a better choice.
You can try something like this:
RIGHT('0000' + TRIM(column), 4)
There are a few variations, here is another:
Left("0000", 4 - Len(Cstr(Trim(column)))) & Cstr(Trim(column))
Sometimes the Len command returns the length minus 1 with numeric values so the Cstr is there to avoid this.

TSQL: No value instead of Null

Due to a weird request, I can't put null in a database if there is no value. I'm wondering what can I put in the store procedure for nothing instead of null.
For example:
insert into blah (blah1) values (null)
Is there something like nothing or empty for "blah1" instead using null?
I would push back on this bizarre request. That's exactly what NULL is for in SQL, to denote a missing or inapplicable value in a column.
Is the requester experiencing grief over SQL logic with NULL?
edit: Okay, I've read your reply with the extra detail about this job assignment (btw, generally you should edit your original question instead of posting more information in an answer).
You'll have to declare all columns as NOT NULL and designate a special value in the domain of that column's data type to signify "no value." The appropriate value to choose might be different on a case by case basis, i.e. zero may signify nothing in a person_age column, but it might have significance in an items_in_stock column.
You should document the no-value value for each column. But I suppose they don't believe in documentation either. :-(
Depends on the data type of the column. For numbers (integers, etc) it could be zero (0) but if varchar then it can be an empty string ("").
I agree with other responses that NULL is best suited for this because it transcends all data types denoting the absence of a value. Therefore, zero and empty string might serve as a workaround/hack but they are fundamentally still actual values themselves that might have business domain meaning other than "not a value".
(If only the SQL language supported a "Not Applicable" (N/A) value type that would serve as an alternative to NULL...)
Is null is a valid value for whatever you're storing?
Use a sentry value like INT32.MaxValue, empty string, or "XXXXXXXXXX" and assume it will never be a legitimate value
Add a bit column 'Exists' that you populate with true at the same time you insert.
Edit: But yeah, I'll agree with the other answers that trying to change the requirements might be better than trying to solve the problem.
If you're using a varchar or equivalent field, then use the empty string.
If you're using a numeric field such as int then you'll have to force the user to enter data, else come up with a value that means NULL.
I don't envy you your situation.
There's a difference between NULLs as assigned values (e.g. inserted into a column), and NULLs as a SQL artifact (as for a field in a missing record for an OUTER JOIN. Which might be a foreign concept to these users. Lots of people use Access, or any database, just to maintain single-table lists.) I wouldn't be surprised if naive users would prefer to use an alternative for assignments; and though repugnant, it should work ok. Just let them use whatever they want.
There is some validity to the requirement to not use NULL values. NULL values can cause a lot of headache when they are in a field that will be included in a JOIN or a WHERE clause or in a field that will be aggregated.
Some SQL implementations (such as MSSQL) disallow NULLable fields to be included in indexes.
MSSQL especially behaves in unexpected ways when NULL is evaluated for equality. Does a NULL value in a PaymentDue field mean the same as zero when we search for records that are up to date? What if we have names in a table and somebody has no middle name. It is conceivable that either an empty string or a NULL could be stored, but how do we then get a comprehensive list of people that have no middle name?
In general I prefer to avoid NULL values. If you cannot represent what you want to store using either a number (including zero) or a string (including the empty string as mentioned before) then you should probably look closer into what you are trying to store. Perhaps you are trying to communicate more than one piece of data in a single field.