You are on page 1of 5

To avoid from encountering this error message, the assigning of the values into the local variables has

to be separated from the insertion of the same values in to a table. The following script separates the two processes to accomplish the i ntended task: DECLARE DECLARE DECLARE DECLARE DECLARE @CustomerName @Address @City @StateCode @ZIPCode VARCHAR(100) VARCHAR(100) VARCHAR(50) CHAR(2) VARCHAR(5)

SELECT TOP 1 @CustomerName = [CustomerName], @Address = [Address], @City = [City ], @StateCode = [State], @ZIPCode = [ZIPCode] FROM [dbo].[Customers] WHERE [State] = 'NY' INSERT INTO [dbo].[CustomersNY] ( [CustomerName], [Address], [City], [State], [Z IPCode] ) VALUES ( @CustomerName, @Address, @City, @State, @ZIPCode ) GO ----Create TestTable CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100)) ----INSERT INTO TestTable using SELECT INSERT INTO TestTable (FirstName, LastName) SELECT FirstName, LastName FROM Person.Contact WHERE EmailPromotion = 2 ----Verify that Data in TestTable SELECT FirstName, LastName FROM TestTable ----Clean Up Database DROP TABLE TestTable GO CREATE TABLE [tempdb].[dbo].[myTempTable]( [backup_set_id] [int] NOT NULL, [name] [nvarchar](128) NOT NULL, [filegroup_id] [int] NOT NULL, [filegroup_guid] [uniqueidentifier] NULL, [type] [char](2) NOT NULL, [type_desc] [nvarchar](60) NOT NULL, [is_default] [bit] NOT NULL, [is_readonly] [bit] NOT NULL, [log_filegroup_guid] [uniqueidentifier] NULL ) ON [PRIMARY]

GO INSERT INTO [tempdb].[dbo].[myTempTable] ( [backup_set_id] ,[name] ,[filegroup_id] ,[filegroup_guid] ,[type] ,[type_desc] ,[is_default] ,[is_readonly] ,[log_filegroup_guid]) SELECT [backup_set_id] ,[name] ,[filegroup_id] ,[filegroup_guid] ,[type] ,[type_desc] ,[is_default] ,[is_readonly] ,[log_filegroup_guid] FROM [msdb].[dbo].[backupfilegroup] GO SELECT * FROM [tempdb].[dbo].[myTempTable] ; GO DROP TABLE [tempdb].[dbo].[myTempTable] ; ---------------------xhttp://www.bigresource.com/MS_SQL-INSERT-INTO-SELECT-using-local-Variables--FQF 0p5zl.html Stored Procedure - Local Variables Show As NULL

I have a stored procedure where I gather some data and then insert the data int o a table variable. I then attempt to go through each row of the table variable , asign the values to local variables to be inserted into other tables. However , the local variables show as NULL.BEGIN DECLARE @tblcontact table ( SOKey int, Cntctkey varchar(60), Cntctownerkey int, LASTNAME varchar(32), FIRSTNAME varchar(32), WORKPHONE varchar(32), EMAIL varchar(128), processed int DEFAULT 0 ) INSERT INTO @tblcontact (SOKey, Cntctkey, Cntctownerkey, LASTNAME, FIRSTNAME, WO RKPHONE, EMAIL) SELECT ... DECLARE @ID int, @sokey int, @cntctkey int, @cntctownerkey int, @name varchar(65), @email varchar(128), @phone varchar(32) WHILE EXISTS (SELECT * FROM @tblcontact WHERE processed = 0) BEGIN SELECT @ID = MIN(SOKey) FROM @tblcontact WHERE processed = 0 SELECT @cntctkey = (CAST(LTRIM(REPLACE(Cntctkey,'CN',' '))AS int)),@cntctownerke y = Cntctownerkey, @name = FIRSTNAME + ' ' + LASTNAME, @phone = WORKPHONE, @emai l = EMAIL, @sokey = SOKey FROM @tblcontact WHERE @ID = SOKey AND @cntctkey <> '43778' INSERT INTO tciContact (Cntctkey, Cntctownerkey, CreateType, EMailAddr, EmailFor mat, EntityType, ExtUser, Name, Phone, UpdateCounter) VALUES (@cntctkey, @cntctownerkey, '0', @email, '3', '401', '0', @name, @phone, '0') UPDATE tsoSalesOrder SET Cntctkey = @cntctkey, UserFld4 = 'temp' WHERE SOKey = @sokey UPDATE @tblcontact SET processed = 1 WHERE @ID = SOKey END END --------------------------http://stackoverflow.com/questions/17349247/assigning-results-of-sql-query-to-lo cal-variables declare @name varchar(30) select @name = (select name from dummyTable where id = 10) But what if I have to assign multiple column values to multiple local variables? Say I have @address, @serialNumber, @grade, @phoneNumber.

Do I have to perform multiple select statements? Like this select @address = (select address from dummyTable where id = 10) select @serialNumber = (select serialNumber from dummyTable where id = 10) .... Is there a way I can do this assignment in 1 select statement? Try this below select @address = address , @serialNumber = serialNumber from dummyTable where id = 10 ---------------------------http://stackoverflow.com/questions/5262513/select-multiple-rows-into-one-variabl e-in-sql-query DECLARE @t TABLE (id int, ReplyText varchar(100)) INSERT INTO @t (id, ReplyText) VALUES (1, 'So Long,') INSERT INTO @t (id, ReplyText) VALUES (2, 'And Thanks for') INSERT INTO @t (id, ReplyText) VALUES (3, 'All of the Fish!') ---------------------------------http://www.dreamincode.net/forums/topic/269927-select-multiple-values-into-local -variable/ SELECT multiple values into local variable I haven't used MSSQL like this for years, but from what I remember, those types of variables are scalar. They can only hold one value, so each row from the SELE CT would just overwrite the value set by the previous row. You can, however, define variables as tables. Then you can INSERT and SELECT fro m it just like a normal table. DECLARE @BusinessUnit AS Table( [id] INT ); INSERT INTO @BusinessUnit([id]) SELECT BU.ID FROM LookupTables BU WHERE BU.AttributeName = 'BusinessUnit'; SELECT ... WHERE BusinessUnit IN (SELECT [id] FROM @BusinessUnit) --SELECT ... FROM [Table] t INNER JOIN @BusinessUnit bu ON t.ID = bu.ID ----------------------------------------http://www.mssqltips.com/sqlservertip/1888/when-to-use-set-vs-select-when-assign ing-values-to-variables-in-sql-server/ Part 2. Assign retrieved values to multiple variables DECLARE @name VARCHAR(50) DECLARE @productNo VARCHAR(25) DECLARE @color VARCHAR(15) SET @name =(SELECT [Name] FROM Production.Product WHERE ProductID = 320) SET @productNo = (SELECT ProductNumber FROM Production.Product WHERE ProductID = 320)

SET @color = (SELECT Color FROM Production.Product WHERE ProductID = 320) PRINT @name PRINT @productNo PRINT @color GO --------------------http://li374-23.members.linode.com/wiki/SQL_Server:Variables_-_Local This example sets a cursor variable to an existing cursor DECLARE @titles_cursor CURSOR, @title_id VARCHAR(10)DECLARE all_titles CURSOR FOR SELECT title_id FRO M titlesSET @titles_cursor = all_titles OPEN @titles_cursorFETCH NEXT FROM @ti tles_cursor INTO @title_id WHILE @@fetch_status = 0 --successful fetch BE GIN PRINT @title_id FETCH NEXT FROM @titles_cursor INTO @t itle_id END CLOSE @titles_cursor -- alternatively we could close the curs or with "CLOSE all_titles" -- destroy the original cursor DEALLOCATE all_title s DECLARE @titles_cursor CURSOR, @title_id VARCHAR(10), @another_titles_cursor CUR SORDECLARE all_titles CURSOR FOR SELECT title_id FROM titlesSET @titles_cursor = all_titles OPEN @titles_cursor-- the following SET statement sets a cursor v ariable to another cursor variable SET @another_titles_cursor = @titles_cursor FETCH NEXT FROM @another_titles_cursor INTO @title_id WHILE @@fetch_status = 0 --successful fetch BEGIN PRINT @title_id FETCH NEXT FROM @another_titles_cursor INTO @title_id END CLOSE @another_titles_cur sor DEALLOCATE all_titlesPRINT 'destroyed the main cursor' PRINT 'scrolling th rough the cursor variable next'OPEN @another_titles_cursor FETCH NEXT FROM @ano ther_titles_cursor INTO @title_id WHILE @@fetch_status = 0 --successful fetch BEGIN PRINT @title_id FETCH NEXT FROM @another_titles _cursor INTO @title_id END CLOSE @another_titles_cursor DEALLOCATE @anot her_titles_cursorPRINT 'destroyed the cursor variable' PRINT 'now try scrolling through the variable again'OPEN @another_titles_cursor FETCH NEXT FROM @anothe r_titles_cursor INTO @title_id WHILE @@fetch_status = 0 --successful fetch BEGIN PRINT @title_id FETCH NEXT FROM @another_titles_cu rsor INTO @title_id END

You might also like