CTE插入语句,如果表名是动态的,怎么写?
CTE插入语句,如果表名是动态的,怎么写?
这个帖子http://bbs.csdn.net/topics/390536906?page=1#post-395208302
DECLARE @count INTSET @count = 30000 ;WITH cte1 AS(SELECT num = 1 UNION ALL SELECT 1), cte2 AS(SELECT num = 1 FROM cte1 a, cte1 b), cte3 AS(SELECT num = 1 FROM cte2 a, cte2 b), cte4 AS(SELECT num = 1 FROM cte3 a, cte3 b), cte5 AS(SELECT num = 1 FROM cte4 a, cte4 b), cteNum as(SELECT num = ROW_NUMBER() OVER(ORDER BY GETDATE()) FROM cte5) INSERT INTO yourtablename(ss) --插入语句 SELECT TOP(@count) num = A.ch+RIGHT('000'+RTRIM(B.num), 4) FROM( SELECT TOP(@count/10000+1) ch = CHAR(num+64) FROM cteNum ) A CROSS JOIN( SELECT TOP(10000) num=num-1 FROM cteNum ) B ORDER BY A.ch, B.num
DECLARE @count INT, @tablename NVARCHAR(255), @sql NVARCHAR(MAX)
SET @count = 30000 --输入你想要生成的数量
SET @tablename = 'yourtablename'
SET @sql = N'
;WITH
cte1 AS(SELECT num = 1 UNION ALL SELECT 1),
cte2 AS(SELECT num = 1 FROM cte1 a, cte1 b),
cte3 AS(SELECT num = 1 FROM cte2 a, cte2 b),
cte4 AS(SELECT num = 1 FROM cte3 a, cte3 b),
cte5 AS(SELECT num = 1 FROM cte4 a, cte4 b),
cteNum as(SELECT num = ROW_NUMBER() OVER(ORDER BY GETDATE()) FROM cte5)
INSERT INTO '+ @tablename +' --插入语句写在这儿, 楼主看一下CTE的用法就明白了。上面用了6个CTE
SELECT TOP(@count) num = A.ch+RIGHT(''000''+RTRIM(B.num), 4)
FROM
(
SELECT TOP(@count/10000+1) ch = CHAR(num+64)
FROM cteNum
) A
CROSS JOIN
(
SELECT TOP(10000) num=num-1
FROM cteNum
) B
ORDER BY A.ch, B.num
'
--PRINT @sql
EXEC sp_executesql @sql, N'@count INT', @count