SQL Server – Generate data in Microsoft SQL Server Management Studio

The legend says that when the chess was invented, the inventor was asked to pick a price from the local king. Thus, he asked for one grain for the first cell of the chess board, 2 for the second, 4 for the third, 8 for the fourth, 16 for the fifth etc. At the end, there was not enough grain in the whole country to pay him. How much grain did he need per cell of the chess board?

We may calculate it easily with SQL and generate a table as well.topalov

Thus, we simply create a table Named Money with 3 columns – AutoId, Cell and PaidPerCell.

To make it easier, we generate the first value in the table like this:

sql1

Then, after already having something generated, we design a query that takes the max value of the column and either increments it by one (for the cell column) or doubles it (for the PaidPerCell) column. In order to tell the SQL Server Management Studio to add data, we should Set the identity insert to ON, before adding it. We may set it to OFF later.

Here comes the code:

SET IDENTITY_INSERT Money ON
DECLARE @I int =1
WHILE @I < 64 BEGIN
	SET @I = @I+ 1
	INSERT INTO Money(Cell, PaidPerCell)
	SELECT
		Max(Cell)+1,
		Max(PaidPerCell)*2
	FROM 
		Money
END 
GO
SET IDENTITY_INSERT Money OFF

 

This is the result:

results

Thank you for your interest in my site 😀