简体   繁体   English

SQL存储过程中的AZ循环

[英]A-Z loop in SQL Stored Procedure

For a project, I have to loop through the alphabet and run a search for each letter against some values in a database. 对于一个项目,我必须遍历字母并针对数据库中的某些值来搜索每个字母。 The function would return the number of matches for each letter. 该函数将返回每个字母的匹配数。

I would like to be able to do this in a SQL Stored Procedure, but I'm not certain how I could do a 'FOR letter = A to Z' loop in a SP. 我希望能够在SQL存储过程中执行此操作,但是我不确定如何在SP中执行“ FOR letter = A to Z”循环。 Does anyone know how this could be done? 有谁知道该怎么做?

it depends according to alphabet if you only need English characters you can do a loop from 65 (ascii for A) and 90 (Z) and use char letter = (char)i to get the letter. 如果您只需要英文字符,则根据字母表而定,您可以从65(A为ascii)和90(Z)组成一个循环,并使用char letter = (char)i来获取字母。

If you also need non-English ones just set a web config setting "ABC......Z" and loop through it. 如果您还需要非英语语言的用户,则只需将网络配置设置为“ ABC ...... Z”并循环浏览即可。

with ATable(c) as
(
  select cast('A' as CHAR(1)) as c
  union all
  select CHAR(ASCII(c)+1) as C from ATable where C<'Z'

)
select * from ATable

SQLFiddle demo SQLFiddle演示

Use a loop going from 65 (A) to 90 (Z), and use the T-SQL CHAR() function . 使用从65(A)到90(Z)的循环,并使用T-SQL CHAR()函数

Of course, I'm assuming that you are using a SQL Server database. 当然,我假设您正在使用SQL Server数据库。 If not, please post the DB you're using. 如果没有,请发布您正在使用的数据库。

You need to use "group by" and possibly include "count" in the query too. 您需要使用“分组依据”,并且可能在查询中也包含“计数”。 you can find further information here http://msdn.microsoft.com/en-us/library/ms177673.aspx 您可以在此处找到更多信息http://msdn.microsoft.com/zh-cn/library/ms177673.aspx

;WITH Alphabet AS 
(
    SELECT CHAR(65) AS Letter, 65 AS Code
    UNION ALL
    SELECT CHAR(Code + 1),  Code + 1
    FROM Alphabet
    WHERE Code < 90
) 

SELECT Letter 
FROM Alphabet
WITH alpha AS
(
    SELECT 65 AS c
    UNION ALL
    SELECT c + 1 FROM alpha
    WHERE c < 90
)
SELECT CHAR(c) FROM alpha

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM