简体   繁体   中英

Sql server - Windowed functions can only appear in the SELECT or ORDER BY clauses

I am trying to insert records into a table and need to insert the the column SubscriberWeightingID that should be sequential order in an existing table ALO_DimSubscriberWeighting in Sql sever database. Ideally the SubscriberWeightingID should be latest based on that table and should continue in sequential order for the remaining. This is what I tried but getting error How do i achieve that I have used the orber by clause but it is still complaining. Is there another way to do it. I have basically 50 such inserts to execute

insert into ALO_DimSubscriberWeighting ([SubscriberWeightingID],[SubscriberNK],[WeightingAmount],[IsActive]) values ((ROW_NUMBER() OVER(ORDER BY [SubscriberWeightingID]),'NSFR80R0040C0090','0',1)   
insert into ALO_DimSubscriberWeighting ([SubscriberWeightingID],[SubscriberNK],[WeightingAmount],[IsActive]) values ((ROW_NUMBER() OVER(ORDER BY [SubscriberWeightingID]),'NSFR80R0040C0100','0',1)   
insert into ALO_DimSubscriberWeighting ([SubscriberWeightingID],[SubscriberNK],[WeightingAmount],[IsActive]) values ((ROW_NUMBER() OVER(ORDER BY [SubscriberWeightingID]),'NSFR80R0040C0110','0',1) 

Error

Invalid column name 'SubscriberWeightingID'.
Msg 4108, Level 15, State 1, Line 1
Windowed functions can only appear in the SELECT or ORDER BY clauses

If you want to manually increment an id, you can use:

insert into ALO_DimSubscriberWeighting ([SubscriberWeightingID],[SubscriberNK],[WeightingAmount],[IsActive]) 
    select coalesce(max(SubscriberWeightingID) + 1, 1), 'NSFR80R0040C0090', '0', 1) 
    from ALO_DimSubscriberWeighting;

This mechanism is highly NOT recommended, because it is not thread-safe. Different insert s can insert the same value.

However, if you are stuck in a situation where you have a table with no identity column and no column defaulted to a sequence, then this is one way to do what you want. It should only be used until you fix the database to automatically generate the values.

You can use identity column to achieve that. However if you want to achieve that as you tried in your code then please try this:

insert into ALO_DimSubscriberWeighting ([SubscriberWeightingID],[SubscriberNK],[WeightingAmount],[IsActive]) 
values ((select isnull(max([SubscriberWeightingID]),0)+1 
from ALO_DimSubscriberWeighting),'NSFR80R0040C0090','0',1)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM