回答

收藏

用cte创建while循环

技术问答 技术问答 274 人阅读 | 0 人回复 | 2023-09-14

如何从while循环中创建sql server cte# x  ^" W, L- N8 }: G7 R7 m
这样的循环
+ `! K$ I- v0 b- H4 n+ \, A3 y) {; S  declare @ind as int( j* q/ L# Q: T8 {
  declare @code as nvarchar
9 k* n0 l, y+ x' _; m( C1 r  set @ind  = 09 ]4 _) R0 f% r( R
   while @ind 如果需要表:
) ]5 J- {& J; h2 ?2 f+ L;WITH Sec(Number) AS 0 j, ]7 y' O, T% J' R
(/ ?4 V, m. {7 s! {) e
    SELECT 0 AS Number
- a; i- ^* S# q    UNION ALL
- p9 f* n1 O" h    SELECT Number + 1
& ]" b7 Z9 N! v    FROM Sec
3 m2 b0 s: a- L0 Y    WHERE Number 如果您需要一个字符串:. ?9 a  @8 ?5 g0 p9 t, ?. \
;WITH Sec(Number) AS 2 b, l6 T: J& ~1 m9 t, U
(
, ~) e$ s6 n# p    SELECT 0 AS Number
% L; C3 K9 J% L# B    UNION ALL
, G4 X* A  R4 Q    SELECT Number + 1
' x2 N' b4 w* \% P    FROM Sec
$ ?5 t- @$ a. I# M  @    WHERE Number < 884
9 Z& q6 E) Q' a3 ^6 f( z% V' R). F+ r( Z* g5 ]' T; M
SELECT STUFF(a.[Str], 1, 1, '')' U3 V) a3 j2 S2 ]2 n
FROM
3 V# U. a& q/ V(
$ e+ E% r: G" Q5 C3 i$ q    SELECT (SELECT ',' + CAST(Number AS NVARCHAR(3)) 2 ^# Y2 l- v8 s- G, H6 K
    FROM Sec9 B2 m; s  z# V% E2 W+ L
    FOR XML PATH(''), TYPE
2 B2 X% M1 j4 [/ P0 R3 Y    ).value('.','varchar(max)') AS [Str] 5 ~# o' p7 L. m( P9 k) V
) AS a6 y' u& R+ p$ j1 v& M) e' I
OPTION(MAXRECURSION 0)
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则