Let's say I have three columns:
id, username, password
As you know, id values are integers. So how can I select id as a string value?
Note that: This is a query that I want to perform on a MSDB server. I couldn't tag because of low reputation points.
Computers can only understand numbers, so an ASCII code is the numerical representation of a character
(asciitable.com)
The ascii function
Returns the ASCII code value of the leftmost character of a character expression.
SQL Server 2014 - String Functions - ASCII (Transact-SQL)
it returns INT and can be convert to TINYINT
SELECT convert(tinyint,ascii('u'))
Try Cast or Convert (assuming T-SQL)j. Here's another helpful link.
SELECT CAST(id as varchar) FROM ...
Related
select CONCAT(convert(char, 123), 'sda');
Or
select convert(char, 123) + 'sda'
Or
select ltrim(convert(char, 123) + 'sda')
Output is:
How can I get the output without those spaces?
The problem here is 2 fold. Firstly that you are converting to a char, which is a fixed width datatype, and secondly that you aren't defining the length of your char, therefore the default length is used. For CAST and CONVERT that's a char(30).
So, what you have to start is convert(char, 123). This converts the int 123 to the fixed width string '123 '. Then you concatenate the varchar(3) value 'sda' to that, resulting in '123 sda'. This is working exactly as written, but clearly not as you intend.
The obvious fix would be to use a varchar and define a length, such as CONCAT(CONVERT(varchar(5),123),'sda') which would return '123sda', however, all of the CONCAT function's parameters are a string type:
string_value
A string value to concatenate to the other values. The CONCAT function requires at least two string_value arguments, and no more than 254 string_value arguments.
This means you can simply just pass the value 123 and it'll be implicitly cast to a string type: CONCAT(123,'sda').
To reiterate my comment's link too: Bad Habits to Kick : Declaring VARCHAR without (length)
You are using char while you probably want [n]varchar(...): the former pads the string with white spaces, while the latter does not:
concat(convert(varchar(10), 123), 'sda');
But simpler yet: concat() forces the conversion of its arguments to the correct datatype by default, so this should do it:
concat(123, 'sda')
First, in SQL Server, never us char or related string definitions without a length. SQL Server requires a length and the default depends on the context. If you depend on the default length your code has a bug just waiting to happen.
Second, char is almost never what you want. It is a fixed length string, with shorter strings padded with spaces.
If you want an explicit conversion use varchar, variable length strings:
select convert(varchar(255), 123) + 'sda'
Or dispense with the explicit conversion and use concat():
select concat(123, 'sda')
As the others have already pointed out the root cause of the issue, if you cannot edit the datatype, you can always use SELECT CONCAT(TRIM(CONVERT(char,123)),'sda'). Although it's highly recommended to either use varchar(n) or give exclusive length of char as it is kind of pointless to create fixed length string and then reduce the length by using TRIM. varchar(30) would perfectly fit in here as the length can still NOT exceed the 30 symbols, but would not use all the length if the string is shorter.
Lets refer to Microsoft docs:
When n isn't specified in a data definition or variable declaration statement, the default length is 1. If n isn't specified when using the CAST and CONVERT functions, the default length is 30.
Reference: https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver15#remarks
So, You have Convert(char, 123), and you did not specify the n for char, so your code is equal to Convert(char(30), 123).
Now it is clear why you have many space characters. To resolve the problem simply use variant length character datatypes such as varchar instead, however I recommend you to always use character datatypes with length. (Same as what #GordonLinoff posted: https://stackoverflow.com/a/63467483/1666800)
select convert(varchar, 123) + 'sda'
need to see if a taxid field contains letters or any special characters:. *,!,?,#,#,$,&,+,(,),/
How can I write this SQL?
Oracle has regexp_like:
select * from tablename where regexp_like(columnname, '[*!?##$&+()/]');
Here is the best way to display all the taxid's that are NOT entirely composed of digits:
select taxid
from your_table
where translate(taxid, '.0123456789', '.') is not null
TRANSLATE will "translate" (replace) each period in the input with a period in the output. Since the other characters in the second argument do not have a corresponding character in the third argument, they will simply be deleted. If the result of this operation is not null, then the taxid contains at least one character that is not a digit. If taxid is all digits, the result of the operation is null. Note that the period character used here is needed, due to an oddity in Oracle's definition of TRANSLATE: if any of its arguments is null, then so is its return value. That doesn't make a lot of sense, but we must work with the functions as Oracle defined them.
I need to extract a report from some tables using db2 having pgm(dnatiaul).
Using a query i want to get the below output with first char to be spaces.
ex: integer(16)
54457750
49457750
o/p: char(int(16))
54457750
49457750
As i am trying to convert it to char it is aligning to left.
I tried Lpad which gives me **extra length i.e (18) + '.' also
Help me
LPAD is the right choice, but you would need to specify how long the result string needs to be. This can be done using CAST. Here I cast the result to 10 characters.
db2 "select cast(lpad(123422,10,' ') as char(10)) as testme from sysibm.sysdummy1"
TESTME
----------
123422
1 record(s) selected.
DIGITS(integer_column_name) will give you a character string of CHAR(10) with the numeric value right-justified and left-filled with zeroes. Thus, an integer column containing 543210 will become a character string containing 0000543210.
Likewise, DIGITS(small_integer_column_name) will give you a character string of CHAR(5)
I have an integer column in my table. It is product id and has values like
112233001
112233002
113311001
225577001
This numbering (AABBCCDDD) is formed of 4 parts:
AA : first level category
BB : second level category
CC : third level category
DDD : counter
I want to check condition in my SELECT statement to select rows that for example have BB = 33 and AA = 11
Please help
Would this suffice:
select x from table where field >= 113300000 and field < 113400000
SELECT * FROM YOURTABLE
WHERE
substr(PRODUCT_ID, 3, 2)='33'
AND
substr(PRODUCT_ID, 1, 2)='11'
OR
SELECT * FROM YOURTABLE
WHERE
PRODUCT_ID LIKE '11%33%'
and yes in short you have to convert to string
reference of substr
Purpose
The SUBSTR functions return a portion of char, beginning at character position, substring_length characters long. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters. SUBSTRC uses Unicode complete characters. SUBSTR2 uses UCS2 code points. SUBSTR4 uses UCS4 code points.
If position is 0, then it is treated as 1.
If position is positive, then Oracle Database counts from the beginning of char to find the first character.
If position is negative, then Oracle counts backward from the end of char.
If substring_length is omitted, then Oracle returns all characters to the end of char. If substring_length is less than 1, then Oracle returns null.
char can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Both position and substring_length must be of datatype NUMBER, or any datatype that can be implicitly converted to NUMBER, and must resolve to an integer. The return value is the same datatype as char. Floating-point numbers passed as arguments to SUBSTR are automatically converted to integers.
Select field from table where substr(field,,) = value
This seems like it could work. Otherwise you may have to cast them as strings and parse the values out that you need which would make your queries much slower.
SELECT *
FROM table t
WHERE t.field >= 113300000
AND t.field < 113400000
u need to use _ wildcard char -
SELECT *
FROM TABLE
WHERE
FIELD LIKE '1133_____'
here, each _ is for one char. So you need to put the same number of _ to keep the length same
I want to be able to differentiate between a string that is alphnumeric and a string that is in hex format.
My current query is:
<columnName> LIKE '?_____=' + REPLICATE('[0-9A-Fa-f]',16)
I found this method of searching for hex ID's online and I thought it was working. However after getting a significantly larger sample size I can see a high false positive rate in my results. The problem is that this gives me all the results I do want but it also gives me a bunch of results I dont care about. For example:
I want to see:
<url>.php?mains=d7ad916d1c0396ff
but i dont want to see:
<url>.php?mblID=2007012422060265
The difference between the 2 strings is that the 16 characters at the end that i want to collect are all numeric and not a hex ID. What are some ways you guys use to limit the results to hex ID only? Thanks in advnace.
UPDATE:
Juergen brought up a good point, the second number could be a hex value to. Not all hex numbers contain [a-F]. I would like to rephrase the question to state that I am looking for an ID with both letters and numbers in it, not just numbers.
The simplest way is just to add a separate clause for that restriction:
<columnName> LIKE '?_____=' + REPLICATE('[0-9A-Fa-f]',16)
AND <columnName> NOT LIKE '?_____=' + REPLICATE('[0-9]',16)
It should be fairly simple to determine if a string contains only numbers...
Setting up a test table:
CREATE TABLE #Temp (Data char(32) not null)
INSERT #Temp
values ('<url>.php?mains=d7ad916d1c0396ff')
,('<url>.php?mblID=2007012422060265 ')
Write a query:
SELECT
right(Data, 16) StringToCheck
,isnumeric(right(Data, 16)) IsNumeric
from #Temp
Get results:
StringToCheck IsNumeric
d7ad916d1c0396ff 0
2007012422060265 1
So, if the IsNumeric function returns 0, it could be a hex string.
This makes several assumptions:
The rightmost 16 characters are what you want to check
You only ever hit 16 characters. I don't know when the string would get too long to check.
A non-numeric character means hex. Any chance of "Q" or "~" being embedded in the string?