Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

SQL Server 2012 : create a new table with instant 1000 record that contains three @variable in int and varchar

I want to create a new table with multiple variables: @id as int, @lastname as varchar and @amount as money. The three variables should change in a sequential manner

Example of expected result:

#id      #lastname    #amount
-------------------------------
1        Ben1         100
2        Ben2         101 
3        Ben3         103
.        Ben4         104
.        .            .
1000     Ben1000      .1000

I appreciate everyone's input

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is similar to "How To Create a Tally Table" problem. A sample solution is below:

WITH Tally (n) AS (
     -- 1000 rows
     SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
     FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
        CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
        CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
   )
-- INSERT INTO [TableOfYourChoice]
SELECT n, 'Ben' + CONVERT( VARCHAR, n ), n + 100
FROM Tally;

Note: if you want amount to start from 100, then change n + 100 to n + 99

Example adapted from examples at http://www.sqlservercentral.com/blogs/dwainsql/2014/03/27/tally-tables-in-t-sql/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...