10

I want to declare a table variable in sql server which will have some hard coded values in it. I tried:

DECLARE @tbl TABLE(Id int) = (1, 2, 3, 4, 5) -- gives error

and this didn't work either:

DECLARE @tbl TABLE(Id int) 
INSERT INTO @TBL SELECT * FROM (1, 2, 3, 4, 5) -- also gives error

isn't there any way to create a table with hard coded existing values?

2 Answers 2

24

The syntax you want is:

DECLARE @tbl TABLE(Id int);

INSERT INTO @tbl (id)
   VALUES (1), (2), (3), (4), (5);

Here is a db<>fiddle.

Sign up to request clarification or add additional context in comments.

3 Comments

Ohhhh yeah, I remembered it now, actually had used it this way very long ago. many many thanks
@AshkanMobayenKhiabani: Worth noting is that VALUES can be a complete replacement for a TABLE declaration, depending on how the table is used (SELECT * FROM (VALUES (1), (2), (3), (4), (5)) T(Id)), especially if it's "hard-coded" (though not necessarily if used multiple times, of course).
@JeroenMostert yeah I know that, but the reason I'm doing this way is because it is going to be used many many times for tens of queries so I want to be able to easily change it for all. the reason I asked the question was for learning purpose mostly
3

In case your data is a string

DECLARE @tbl TABLE(Id int) 
INSERT INTO @TBL 
 SELECT value from string_split('1, 2, 3, 4, 5',',')

 Select * from @tbl

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.