3

How to insert static values in table variable using select statement (without using multiple insert statment) in MS SQL Server.

e.g

Declare @xyz table(
abc varchar(10),
pqr varchar(10)
)
insert into @xyz(abc, pqr) values('a1', 'p1')
insert into @xyz(abc, pqr) values('a2', 'p2')
insert into @xyz(abc, pqr) values('a3', 'p3')

Instead, Is there a way to write something like below ?

insert into @xyz(abc, pqr)
select abc, pqr
from (
    'a1', 'p1',
    'a2', 'p2',
    'a3', 'p3'
)res

Thank you,

3 Answers 3

3
insert into @xyz(abc, pqr)
select abc, pqr
from (VALUES
    ('a1', 'p1'),
    ('a2', 'p2'),
    ('a3', 'p3')
)res(abc, pqr)
Sign up to request clarification or add additional context in comments.

Comments

1
insert into @xyz(abc, pqr) values('a1', 'p1'),('a2', 'p2'),('a3', 'p3')

Comments

1

You don't have to repeat the insert statement...

Declare @xyz table(
abc varchar(10),
pqr varchar(10)
)
insert into @xyz(abc, pqr) 
values

('a1', 'p1')
,('a2', 'p2')
,('a3', 'p3')

Or you can nest it with union all

insert into @xyz(abc, pqr) 
select abc, pqr
from
(
    select
    'a1' as abc , 'p1' as pqr
    union all
    select
    'a2', 'p2'
    union all
    select
    'a3', 'p3'
) x

Or a table constructor

insert into @xyz(abc, pqr) 
select abc, pqr
from
(values('a1','p1'),('a2', 'p2'),('a3', 'p3'))  as x(abc, pqr)

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.