我有一个表格tab1,其结构为 -
+-----------+--------+
|columnName |datatype|
+-----------+--------+
|col1 |VARCHAR |
+-----------+--------+
|col2 |VARCHAR |
+-----------+--------+
|col3 |VARCHAR |
+-----------+--------+
|col4 |VARCHAR |
+-----------+--------+
|col5 |VARCHAR |
+-----------+--------+
和样本数据
+----+-------+----+----+----+
|col1|col2 |col3|col4|col5|
+----+-------+----+----+----+
|11 |aaaaaaa|aaaa|aaaa|1111|
+----+-------+----+----+----+
|22 |bbbbbbb|bbbb|bbbb|2a2s|
+----+-------+----+----+----+
|33 |ccccccc|cccc|cccc|a312|
+----+-------+----+----+----+
|44 |ddddddd|dddd|dddd|4444|
+----+-------+----+----+----+
现在我只想检索那些只有col5的行(只有第1行和第4行)。如何在oracle和teradata中编写查询?
答案 0 :(得分:2)
假设列是4个字符(如示例数据中所示),我能想到的唯一可用于两个数据库的代码是:
select t.*
from tab1 t
where substr(t.col5, 1, 1) between '0' and '9' and
substr(t.col5, 2, 1) between '0' and '9' and
substr(t.col5, 3, 1) between '0' and '9' and
substr(t.col5, 4, 1) between '0' and '9';
这有点蛮力。但是当获取适用于多个数据库的SQL时,通常必须限制您使用的功能。
编辑:
字符串长度的函数在Oracle和Teradata中是相同的。因此,对于较短的字符串,您可以这样做:
select t.*
from tab1 t
where substr(t.col5, 1, 1) between '0' and '9' and
(length(t.col5) < 2 or substr(t.col5, 2, 1) between '0' and '9') and
(length(t.col5) < 3 or substr(t.col5, 3, 1) between '0' and '9') and
(length(t.col5) < 4 or substr(t.col5, 4, 1) between '0' and '9');
答案 1 :(得分:1)
如果在Teradata中安装了oTranslate UDF,您可以尝试旧技巧,删除所有数字并检查结果字符串是否为空:
where char_length(oTranslate(col5, '0123456789', '') = 0
Oracle可能类似,可能是:
where length(Translate(col5, '.0123456789', '.') = 0
答案 2 :(得分:0)
你可以使用这个功能
isinteger(科隆)
replace FUNCTION "temp_DB".isinteger(X VARCHAR(20))
RETURNS BYTEINT
LANGUAGE SQL
CONTAINS SQL
DETERMINISTIC
SQL SECURITY DEFINER
COLLATION INVOKER
INLINE TYPE 1
RETURN
CASE
WHEN
CHARACTERS(X) > 18 -- first elimination biggers from bigint
THEN 0
WHEN
TRANSLATE_CHK(X USING unicode_to_latin) <> 0
THEN 0
WHEN
UPPER(X)(CASESPECIFIC) <> LOWER(X)(CASESPECIFIC) -- for letter control
THEN 0
WHEN
CHAR2HEXINT(X) LIKE ANY -- for other controls
(
'%A%','%B%','%C%','%D%','%E%','%F%', -- if hexadecimal codes have a letter that can't be a integer
'%0020%','%0021%','%0022%','%0023%','%0024%','%0025% ','%0026%','%0027%','%0028%','%0029%','%0040%','%0060% ' -- and other characters
)
THEN 0
ELSE 1
END