-1

I'm not sure what FOR is doing in this SQL Server snippet.

ALTER TABLE [dbo].[TableName] 
    ADD DEFAULT (NEXT VALUE FOR [dbo].[TableName_Seq]) FOR [TableName_Key]

When I try to google for FOR clause the only meaningful result I got was this, but I don't think it's relevant

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jimmy Vo
  • 124
  • 2
  • 11
  • [NEXT VALUE FOR (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver15) – Thom A Apr 17 '21 at 14:21
  • [ALTER TABLE (Transact-SQL) - Examples: Adding Columns and Constraints - D. Adding a DEFAULT constraint to an existing column](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-table-transact-sql?view=sql-server-ver15#d-adding-a-default-constraint-to-an-existing-column) – Thom A Apr 17 '21 at 14:24
  • There are **two** `FOR` - which one is the one that's unclear to you?? – marc_s Apr 17 '21 at 14:24
  • Both, to be honest – Jimmy Vo Apr 17 '21 at 14:25

2 Answers2

3

FOR is a keyword of the NEXT VALUE FOR function. It is used to return the next value from the specified sequence object.

FOR is also a keyword of the DEFAULT constraint clause, specifying the target column name of the constraint.

In the context of the DDL in your question, the function result is the default value automatically assign the value when a value is not explicitly specified in INSERT statements.

BTW, it's a best practice to name constraints rather than relying on auto-generated names. This makes subsequent schema modifications easier.

Dan Guzman
  • 43,250
  • 3
  • 46
  • 71
1

FOR by itself has no specific meaning, it depends on context.

In this case, there are 2 usages of FOR:

Lukas S.
  • 5,698
  • 5
  • 35
  • 50