Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

sql server - INSERT statement cannot contain a SELECT statement -sql server2012

    declare @us table(name nvarchar(100),lastname nvarchar(100),UID bigint,available bit);
        declare
        @Name nvarchar(100),
        @lastname nvarchar(100),
        @UID bigint,
        @Avail bit

        insert into @us
        select @name=name,@lastname=lastname,@UID=UID,@Avail=available from Users where available='1'
 select * from @us

I got this error

An INSERT statement cannot contain a SELECT statement that assigns values to a variable.

I searched for this problem but many people used queries like this and they said there is no problem! i'm using sql server 2012, is it a deference between MSSQL2012 and MSSQL2008? and what is the best solution if I want to return a table from my Stored Procedures? what is wrong in my query?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on the information provided in the question, the variables seem to be unnecessary. You can directly do INSERT...SELECT like so:

declare @us table(name nvarchar(100),lastname nvarchar(100),UID bigint,available bit);

insert into @us
select name,lastname,UID,available 
from Users 
where available='1'

select * from @us

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...