vba脚本中的sql多case语句

8tntrjer  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(394)

在excelvba中编写这些多个case-when语句时,我遇到了一个错误。脚本在SQLServer中运行得很好,但在ExcelVBA中正确格式化脚本以使其能够正确运行时遇到了问题。求求你帮忙?!

n3ipq98p

n3ipq98p1#

以下是如何在vba中编写长字符串:

StrQuery = "Select" & _
" case when srvprovid like '01%' then 'AL'" & _
"      WHEN srvprovid like '02%' then 'AK'" & _
"      WHEN srvprovid like '03%' then 'AR'" & _
" ..."

我建议你这样做(只是一个展示想法的示例,没有编写完整的代码):

DECLARE @sample TABLE (srvProvId VARCHAR(10), id INT IDENTITY);
INSERT INTO @sample (srvProvId) VALUES 
('010'),
('01'),
('020'),
('030'),
('040');

DECLARE @states VARCHAR(1000) = 'AL,AK,AR,AZ,CA,CO,CT'; -- DE,DC,FL...
DECLARE @tally TABLE (id INT IDENTITY, abrv CHAR(2));

INSERT @tally (abrv)  
SELECT value FROM STRING_SPLIT(@states, ',') ;

SELECT * 
FROM @sample t1
LEFT JOIN @tally t2 ON t1.srvProvId LIKE RIGHT('0'+CAST(t2.id AS VARCHAR(2)),2)+'%';

相关问题