January 24, 2011 at 2:24 pm
I am trying to create a stored procedure that takes a database name as variable. I am trying to use this name to assign a value from a table to another variable but can't get it to work.
Below is code I am using.
Create procedure Vendors @GPCompany char(5)
as
Declare @SQL varchar(1000)
Declare @Location char(5)
set @SQL = 'set @Location = Select location from Accts where GPDB = ' + @GPCompany
Exec (@SQL)
but it gives error saying @Location has to be defined.
How do I assign a value to this variable using Dynamic SQL
I need to use this variable to make another dynamics SQL query to get other data.
Please help I am stuck here.
January 24, 2011 at 3:26 pm
Hmm, this is the second question today on this same topic - is this homework?
You need to look into the scope of variables, and the usage of sp_executesql. I'll help out more if it's not a homework question.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
January 24, 2011 at 3:35 pm
Why are you using dynamic sql for this?
January 24, 2011 at 3:45 pm
I have to ask the same question, why the dynamic sql. From what I can see it isn't needed.
January 25, 2011 at 8:27 am
Nope, this is not homework. I did look at sp_executesql but could not get it to work. How would I assign this variable the value I need from the dynamic SQL query.
January 25, 2011 at 8:28 am
Can you give me some code without using dynamic SQL for this?
January 25, 2011 at 8:39 am
Sure. You're overthinking it:
CREATE PROCEDURE Vendors @GPCompany CHAR(5)
AS
BEGIN
DECLARE @Location CHAR(5)
SET @Location = (SELECT [Location]
FROM Accts
WHERE GPDB = @GPCompany)
SELECT @Location
END
GO
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply