Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a table variable with existing data in sql server

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?

like image 345
Ashkan Mobayen Khiabani Avatar asked Apr 14 '26 23:04

Ashkan Mobayen Khiabani


2 Answers

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.

like image 85
Gordon Linoff Avatar answered Apr 17 '26 16:04

Gordon Linoff


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
like image 26
John Cappelletti Avatar answered Apr 17 '26 16:04

John Cappelletti