INSERT statement cannot contain a SELECT statement -sql server2012

自古美人都是妖i 提交于 2019-12-13 05:05:36

问题


    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?


回答1:


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



回答2:


Alternate and complex way of doing the same task is the below one. Hope nobody likes this. Just I am showing we have one more alternative way.

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

DECLARE ALLRECORDS CURSOR FOR 
    SELECT name,lastname,UID,available from Users where available='1'

     OPEN ALLRECORDS
     FETCH NEXT FROM ALLRECORDS INTO @Name,@lastname,@UID,@Avail

        WHILE @@FETCH_STATUS = 0
        BEGIN
        INSERT INTO @us    
        SELECT @Name,@lastname,@UID,@Avail 

        FETCH NEXT FROM ALLRECORDS INTO @Name,@lastname,@UID,@Avail
        END
CLOSE ALLRECORDS
DEALLOCATE ALLRECORDS
SELECT * FROM @us


来源:https://stackoverflow.com/questions/25132481/insert-statement-cannot-contain-a-select-statement-sql-server2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!