Daily SQL- renumbered

Daily SQL- renumbered


Since the past few months are using Linq to SQL, T-SQL syntax for that strange to not work.

But in the end the operation of the database or SQL syntax, so this still can not forget the basics better.

To achieve this goal, it is determined to come to a daily SQL, either select, insert, or the built-in functions are good

Familiar with one kind of a day, a year will have 365 kinds, it should be more than enough of it.

Today, there are just two requirements must rearrange a nvarchar type numbers, so from the start it

First to build a data table "reordering" field below

db787128ecb047a48bb5294d8f746fc4

First to the last record of a people taught me, if from a different database or a different table, batch update or insert data come in

You can write


INSERT INTO [My].[dbo].[重新排序]

([编号],[类],[标题])

select '00000000',CategoryName,Description 

from Northwind.dbo.Categories

As long as the number of fields for the types with good, will select all the data behind that the inset to the front of the Table (course also under conditions where)

The results (ID field, I have to defaults newid ())

374d6b4aa5ec43ee9fdd4d0644dd17a7

Well, after the

Suppose I want to do the sorting class, and then sequentially numbered words

First of all to learn is how numbers


select *
, row_number() over(order by [类]) as rnk
from [My].[dbo].[重新排序]

row_number () This function is also full of easy to use, can also be used for paging (With Linq but since I have not used it)

Sort functions: ROW_NUMBER (), RANK () and DENSE_RANK ()

After a will, but it needs something, because I want my number is eight digits

0 insufficient to make up front, it is necessary to use other methods, well it happens before the blog brother Paul was made a few days

T-SQL techniques: generating a "fixed-length string of digits with leading zeros"

Sure enough, the blog regularly watch the Masters can only be good, it is needed to know easy to use

Ever since a direct challenge to a third example, a little further connection with the above syntax


with 暂时table
as
(
select *
, row_number() over(order by [类]) as rnk
from [My].[dbo].[重新排序]
)
update 暂时table
set [编号] =  RIGHT( REPLICATE('0', 8) + CAST(rnk as NVARCHAR), 8)

Basically select reorder this table by adding a sort of class number rnk, giving a temporary table name

Then he update, and then update time, the rnk translated into strings, plus eight replicate to establish a number of 0, then eight digits taken from the right

The result is this

3f6ad223bd844bbbb620cb50eba9353f

After the order by to see more clearly

ebd08a5a1ede4e83a51ab113fd7d82d5

This would solve it. And learn something.

Original: Large column  Day SQL- renumbered


Guess you like

Origin www.cnblogs.com/chinatrump/p/11516603.html