如何在 sql 查询中获取子字符串
How to get Substring in sql query
我试图从 table 名称中的 int 元素中的 0-7 位置获取子字符串,所以当我插入这个
select substring(column_name,0, 6) as new_name from table_name
我得到
SQL Error [42883]: ERROR: function pg_catalog.substring(bigint,
integer, integer) does not exist
Hint: No function matches the given name and argument types. You
might need to add explicit type casts.
Position: 8
org.postgresql.util.PSQLException: ERROR: function
pg_catalog.substring(bigint, integer, integer) does not exist
Hint: No function matches the given name and argument types. You
might need to add explicit type casts. Position: 8
所以在向 varchar(8) 添加一些转换后
select substring(varchar(8),column_name,0, 6) as new_name from table_name
得到这个
SQL Error [42601]: ERROR: syntax error at or near "," Position: 28
org.postgresql.util.PSQLException: ERROR: syntax error at or near ","
Position: 28
我不知道我做错了什么。谢谢。
您可以 cast
将 int
列设为 varchar
,然后从 1
到 7
[=19= 创建一个 substring
]
select substring(cast([your-column] as varchar(100)),1, 7)
示例:
declare @a int ='1234567890';
select substring(cast(@a as varchar(100)),1, 7) as res
输出:
res
1234567
直接投射到文本:
select substring(column_name::text, 1, 7) as new_name
from table_name
请注意 SQL(与类 C 语言不同)使用 1-based 索引,因此第一个字符位于 1
位置。与类 C 语言不同的是,substring 的第二个参数是 length(不是唯一的结束索引)。
我试图从 table 名称中的 int 元素中的 0-7 位置获取子字符串,所以当我插入这个
select substring(column_name,0, 6) as new_name from table_name
我得到
SQL Error [42883]: ERROR: function pg_catalog.substring(bigint, integer, integer) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 8
org.postgresql.util.PSQLException: ERROR: function pg_catalog.substring(bigint, integer, integer) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts. Position: 8
所以在向 varchar(8) 添加一些转换后
select substring(varchar(8),column_name,0, 6) as new_name from table_name
得到这个
SQL Error [42601]: ERROR: syntax error at or near "," Position: 28
org.postgresql.util.PSQLException: ERROR: syntax error at or near "," Position: 28
我不知道我做错了什么。谢谢。
您可以 cast
将 int
列设为 varchar
,然后从 1
到 7
[=19= 创建一个 substring
]
select substring(cast([your-column] as varchar(100)),1, 7)
示例:
declare @a int ='1234567890';
select substring(cast(@a as varchar(100)),1, 7) as res
输出:
res
1234567
直接投射到文本:
select substring(column_name::text, 1, 7) as new_name
from table_name
请注意 SQL(与类 C 语言不同)使用 1-based 索引,因此第一个字符位于 1
位置。与类 C 语言不同的是,substring 的第二个参数是 length(不是唯一的结束索引)。