我有一个SQL查询从数据库中提取客户名称,创建一个具有该名称的客户文件夹。在查询中,我正在查杀斜杠和句点,我也将包含MCDONALD的任何结果更改为SIMPLY“MCDONALDS”。所以MCDONALDS#123就像MCDONALDS一样出现。这是我的询问。
SELECT
CASE WHEN CHARINDEX('MCDONALD', cust_name) = 0
THEN REPLACE(REPLACE([cust_name],'.',''),'--','-')
ELSE 'MCDONALDS'
END cust_name
FROM job,dbo.cust cust_name
WHERE job.cust_id_bill_to = cust_name.cust_code AND
job.job_id = '44321' AND
job.sub_job_id = '2'
所以,结果现在是:
MCDONALDS, BRISTOL-MYERS, TRUMP-CASINO
期望的结果是每个单词的大写和小写..像这样:
Mcdonalds, Bristol-Myers, Trump-Casino
我知道这很简单,但对我而言,如何让它与我的查询的其余部分一起工作,到目前为止,我正在努力工作。
答案 0 :(得分:0)
检查Nimit Dudani回答Here
DELIMITER $$
DROP FUNCTION IF EXISTS `test`.`initcap`$$
CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8
BEGIN
SET @str='';
SET @l_str='';
WHILE x REGEXP ' ' DO
SELECT SUBSTRING_INDEX(x, ' ', 1) INTO @l_str;
SELECT SUBSTRING(x, LOCATE(' ', x)+1) INTO x;
SELECT CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(@l_str,1,1)),LOWER(SUBSTRING(@l_str,2)))) INTO @str;
END WHILE;
RETURN LTRIM(CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2)))));
END$$
DELIMITER ;
用法:
选择initcap('这是测试字符串');
答案 1 :(得分:0)
对于Sql Server,您可以使用this
INITCAP
用户定义的功能代码
IF OBJECT_ID('dbo.InitCap') IS NOT NULL
DROP FUNCTION dbo.InitCap;
GO
CREATE FUNCTION dbo.InitCap (@inStr VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @outStr VARCHAR(8000) = LOWER(@inStr),
@char CHAR(1),
@alphanum BIT = 0,
@len INT = LEN(@inStr),
@pos INT = 1;
-- Iterate through all characters in the input string
WHILE @pos <= @len BEGIN
-- Get the next character
SET @char = SUBSTRING(@inStr, @pos, 1);
-- If the position is first, or the previous characater is not alphanumeric
-- convert the current character to upper case
IF @pos = 1 OR @alphanum = 0
SET @outStr = STUFF(@outStr, @pos, 1, UPPER(@char));
SET @pos = @pos + 1;
-- Define if the current character is non-alphanumeric
IF ASCII(@char) <= 47 OR (ASCII(@char) BETWEEN 58 AND 64) OR
(ASCII(@char) BETWEEN 91 AND 96) OR (ASCII(@char) BETWEEN 123 AND 126)
SET @alphanum = 0;
ELSE
SET @alphanum = 1;
END
RETURN @outStr;
END
GO
测试:
SELECT dbo.InitCap('new york');
结果:纽约
查询
SELECT
dbo.InitCap(CASE WHEN CHARINDEX('MCDONALD', cust_name) = 0
THEN REPLACE(REPLACE([cust_name],'.',''),'--','-')
THEN 'MCDONALDS'
END) cust_name
FROM job,dbo.cust cust_name
WHERE job.cust_id_bill_to = cust_name.cust_code AND
job.job_id = '44321' AND
job.sub_job_id = '2'