I need to write a function to check if a varchar variable value is all zeros.
As the variable is a varchar and not an int I am a bit lost. What would you do?
Thanks a lot
You can use a double-negative with a LIKE test:
#variable NOT LIKE '%[^0]%'
Which says the variable isn't composed of some number of characters, then a character that isn't a 0, followed by some number of characters. The only strings that fail to match that LIKE expression are strings that only contain 0s, and so we use the NOT to invert the result.
(This does also accept an empty string - whether you consider an empty string to be composed of only 0s can be quite an interesting discussion - it certainly doesn't contain any other characters. A simple LEN(#Variable) test can be used if you do choose to reject this)
Related
Can you help me with with TD error?
I just do cast(array_type as varchar(200)) as col1 and it works but when I use this col1 in the comparison to other column, I get:
The arguments of the CAST function must be of the same character data type
What is going on?
Check this reference from Teradata Documentation. It appears that you are casting a character type column with a defined character set to character column with a different character set. To rephrase, you are casting a character to a character, only the charactersets are changing rather than data type, but this is not the intended usage for CAST operation.
In order to change character sets, you will need to use TRANSLATE rather than CAST. Remember that output of TRANSLATE can give errors for non-convertible characters, so you may want to play with its arguments to ignore such errors. Check this Teradata Documentation reference for TRANSLATE.
Remember to check the WITH ERROR argument available with TRANSLATE if you get issues with non-convertible characters. Depending on your use case, you can then either replace the placeholder character with empty string or take some other action on rows containing the placeholders.
How can I check if a string consists of letters or numbers ONLY in Transact-SQL?
Here the string has datatype nchar, 'letters' specifically refer to latin characters. Database environment is Microsoft SQL Server 2014.
Example for desired result:
C172E returns True
412?A returns False //'?' is neither a letter nor a number
I've done some searching but only found the built-in ISNUMERIC() function, which is for numbers only.
Is there a Transact-SQL solution for this problem?
See this similar question about obtaining only fields with alphanumeric data
You can do the following:
FIELD NOT LIKE '%[^a-zA-Z0-9]%'
You can use not like:
(case when str not like '%[^a-zA-Z0-9]%' then 1 else 0 end) as isalnum_flag
This is saying that the string has no non-alphanumberic characters.
You are looking at using Regex to do this. [a-zA-Z] is char, [0-9] is numeric, [a-zA-Z0-9] is both. You mention having to add in spaces? \s is white space characters (this could be more than just the fields.
This one is a bit more involved (more depth).
I'm importing data from one system to another. The former keys off an alphanumeric field whereas the latter requires a numeric integer field. I'd like to find or write a function that I can feed the alphanumeric value to and have it return a number that would be unique to the value passed in.
My first thought was to do a hash, but of course the result of any built in hashes are going to contains letters and plus it's technically possible (however unlikely) that a hash may not be unique.
My first question is whether there is anything built in to sql that I'm overlooking, and short of that I'd like to hear suggestions on the easiest way to implement such a function.
Here is a function which will probably convert from base 10 (integer) to base 36 (alphanumeric) and back again:
https://www.simple-talk.com/sql/t-sql-programming/numeral-systems-and-numbers-conversion-in-sql/
You might find the resultant number is too big to be held in an integer though.
You could concatenate the ascii values of each character of your string and cast the result as a bigint.
If the original data is known to be integers you can use cast:
SELECT CAST(varcharcol AS INT) FROM Table
Does anyone know a good way to count characters in a text (nvarchar) column in Sql Server?
The values there can be text, symbols and/or numbers.
So far I used sum(datalength(column))/2 but this only works for text. (it's a method based on datalength and this can vary from a type to another).
You can find the number of characters using system function LEN.
i.e.
SELECT LEN(Column) FROM TABLE
Use
SELECT length(yourfield) FROM table;
Use the LEN function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
Doesn't SELECT LEN(column_name) work?
text doesn't work with len function.
ntext, text, and image data types will be removed in a future version
of Microsoft SQL Server. Avoid using these data types in new
development work, and plan to modify applications that currently use
them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For
more information, see Using Large-Value Data Types.
Source
I had a similar problem recently, and here's what I did:
SELECT
columnname as 'Original_Value',
LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
N'['+columnname+']' as 'UnicodeStr_Value',
LEN(N'['+columnname+']')-2 as 'True_Char_Count'
FROM mytable
The first two columns look at the original value and count the characters (minus leading/trailing spaces).
I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.
By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.
I need to store Medicare APC codes. I believe the format requires 4 numbers. Leading zeros are relevant. Is there any way to store this data type with verification? How should I store this data (varchar(4), int)?
This kind of issue, storing zero leading numbers that need to be treated as Numeric values on some scenarios (i.e. sorting) and as textual values in others (i.e. addresses) is always a pain and there is no one answer that is best for all users. At my company we have a database that stores numbers as text for codes (not Medicare APC codes) and we must pad them with zero’s so they will sort properly when used in an order operation.
Do not use a numeric data type for this because the item is not a true number but textual data that uses numeric characters. You will not be performing any calculations or aggregates on the codes and so the only benefit to storing them as a number would be to ensure proper sorting of the codes and that can be done with the code stored as text by padding it with zeros where needed. If you sue a numeric data type then any time the code is combined with other textual values you will have to explicitly convert it to CHAR/VARCHAR or let SQL Server do it since implicit conversions should always be avoided that means a lot of extra work for you and the query processor any time the code is used.
Assuming you decide to go with a textual data type the question then is should you use VARCHAR or CHAR and while many who have posted say VARCHAR I would suggest you go with CHAR set to a length of 4. WHY?
The VARCHAR data type is for textual data in which the size (the length or number of characters) is unknown in advance. For this Medicare code we know the length will always be at least 4 and possibly no more than 4 for the foreseeable future. SQL Server handles the storage of the data differently between CHAR and VARCHAR. SQL Server’s BOL (Books On Line) says :
Use CHAR when the size of the column data entries are consistent
Use VARCHAR when the size of the column data varies considerably.
I can’t say for certain this is true for SQL Server 2008 and up but for earlier versions, the use of a VARCHAR data type carries an extra overhead of 1 byte per row of data per column in a table that has a VARCHAR data type. If the data stored is always the same size and in your scenario it sounds like it is then this extra byte is a waste.
In the end it’s up to you as to whether you like CHAR or VARCHAR better but definitely don’t use a numeric data type to store a fixed length code.
That's not numeric data; it's textual data that happens to contain digits.
Use a VARCHAR.
I agree, using
CHAR(4)
for the check constraint use
check( APC_ODE LIKE '[0-9][0-9][0-9][0-9]' )
This will force a 4 digit number only to be accepted...
varchar(4)
optionally, you can still add a check constraint to ensure the data is numeric with leading zeros. This example will throw exceptions in Oracle. In other RDBMS, you could use regular expression checks:
alter table X add constraint C
check (cast(APC_CODE as int) = cast(APC_CODE as int))
If you are certain that the APC codes will always be numeric (that is if it wouldn't change in the near future), a better way would be to leave the database column as is, and handle the formatting (to include leading zeros) at places where you use this field values.
If you need leading 0s, then you must use a varchar or other string data type.
There are ways to format the output for leading 0s without compromising your actual data.
See this blog entry for an easy method.
CHAR(4) seems more appropriate to me (if I understood you right, and the code is always 4 digits).
What you want to use is a VARCHAR data type with a CHECK constraint, using LIKE with a pattern to check for numeric values.
in TSQL
check( isnumeric(APC_ODE) = 1)