I have the following stored procedure:
SET QUOTED_IDENTIFIER OFF;
GO
ALTER PROCEDURE [transactiondb] #dbname1 NVARCHAR(128)
AS
DECLARE #query VARCHAR(1000);
SET #query = "SELECT TOP 10*
FROM #dbname1.dbo.transaction";
EXEC (#query);
GO
When I execute the stored procedure I get the following error:
Must declare the scalar variable "#dbname1"
I am pretty sure this is something to do with the way the variable is being passed, but I am really struggling to understand what is happening or how to correct?
Try with this. it works for me,
Alter PROCEDURE [transactiondb] #dbname1 NVARCHAR(128)
AS
DECLARE #query VARCHAR(1000);
SET #query = 'SELECT TOP 10 *
FROM ' +#dbname1+'.dbo.transaction';
EXEC (#query);
Go
Related
It is necessary to write a procedure that makes a request, which, in turn, should output all the objects of a particular column.
Here is what I tried:
CREATE PROCEDURE AttributeRequest(n CHAR(200))
begin
SELECT n FROM table;
end
But this variable is perceived as the name of the column itself and nothing comes out.
Tell me how to make such a request by the attribute of the object, please
I searched a bit, read the answers below, and I managed to implement this task in the following way:
CREATE PROCEDURE AttributeRequest(n CHAR(200))
begin
SET #t =CONCAT("SELECT ",n ," FROM table");
PREPARE e FROM #t;
EXECUTE e;
end
you will have to use dynamic sql for this
CREATE PROCEDURE AttributeRequest(#n CHAR(200)) AS
begin
declare #query varchar(1000);
set #query = 'select ['+#n+'] FROM table;
exec AttributeRequest #query
end
then you can excute it ,
exec AttributeRequest 'columnname'
I have a sql server stored procedure where I want the table column name to be stored as variable.But I am finding it difficult.
CODE
ALTER PROCEDURE [dbo].[GetLeaveDays]
-- Add the parameters for the stored procedure here
#LeaveType varchar,#AdminId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT #LeaveType FROM CompulsoryLeave WHERE AdminId =#AdminId
END
Where the #Leavetype is the name of the table column.
EDIT
This is how I execute the stored procedure
GetLeaveDays 'Maternity',1
Use dynamic SQL as suggested. In your case you could use the following T-SQL.
You can read docs for dynamic SQL at Dynamic SQL in SQL Server
Keep in mind to always use sp_executesql to execute your dynamically formed queries since it's more secure that using EXEC (#query).
DECLARE #queryString nvarchar(MAX);
SET #queryString = 'SELECT ' + #LeaveType + ' WHERE AdminId = #AdminId';
EXECUTE sp_executesql #queryString,
N'#AdminId int',
#AdminId = #AdminId;
Using the above approach, your stored procedure would now look like the following.
ALTER PROCEDURE [dbo].[GetLeaveDays] -- Add the parameters for the stored procedure here
#LeaveType varchar(5000),
#AdminId int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #queryString nvarchar(MAX);
SET #queryString = 'SELECT ' + #LeaveType + 'FROM CompulsoryLeave WHERE AdminId = #AdminId';
EXECUTE sp_executesql #queryString,
N'#AdminId int',
#AdminId = #AdminId;
END
you can use sp_executesql command for this purpose. You can read this Article to get a nice review on dynamic SQL.
DECLARE #sqlCommand nvarchar(max);
SET #sqlCommand = 'SELECT ' + #LeaveType + ' FROM CompulsoryLeave WHERE AdminId = '''+#AdminId+''''
EXECUTE sp_executesql #sqlCommand, N'#AdminId int', #AdminId = #AdminId;
Im trying to get return form below store procedure but this is not giving me value
can you please say what i am doing mistake in my procedure.
ALTER PROCEDURE CALCWEIGHT1
#EQUATION varchar(255),
#VOLUME decimal(10,2)
AS
BEGIN
declare #SQL varchar(max);
declare #WEIGHT decimal(10,2);
IF(#EQUATION = '') or(#EQUATION is null)
BEGIN
set #EQUATION =' SELECT #WEIGHT = (('+Convert(varchar(10),#VOLUME)+' / 1728.0 * 8.907 *100.0) / 100.0)'
END
else
BEGIN
set #SQL='SELECT #EQUATION= REPLACE('''+#EQUATION+''', ''VOLUME'', '''+Convert(varchar(10),#VOLUME)+''')'
exec #SQL
set #EQUATION='SELECT #WEIGHT= '+#EQUATION+' '
END
execute (#EQUATION)
END
for check i am execute with this value
EXEC CALCWEIGHT1 '',789
Thanks For your comments.
You are just assigning variables. You don't really select anything.
Remove your use of #Weight.
I have a stored procedure in which i am creating an insert statement in a string and then executing the statement.
When i am using SCOPE_IDENTITY() to retrieve the id of newly inserted record it is returning NULL.
Please check the code below -
ALTER PROCEDURE [dbo].[sgi_sp_SaveCompComponent]
-- Add the parameters for the stored procedure here
#Id int output,
#ComponentName nvarchar(50),
#VehicleSystemId nvarchar(10),
#NamingConvension nvarchar(50),
#IsSubcomponent bit=0,
#SubComponentId int=null,
#CompanyID int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #TableName nvarchar(100) ='C'+ cast(#CompanyID as nvarchar(10)) +'_Components',
#AssociatedTable nvarchar(100)='C'+cast(#CompanyID as nvarchar(10))+'_'+ +REPLACE(#ComponentName,' ','');
DECLARE #cmd AS NVARCHAR(max)
-- Insert statements for procedure here
Set #cmd='insert into '+#TableName+ '( ComponentName, VehicleSystemId, NamingConvension, IsSubcomponent, SubComponentId, AssociatedTable) values(''';
set #cmd = #cmd + #ComponentName+''','''+ #VehicleSystemId+''','''+#NamingConvension+ ''','''+cast(#IsSubcomponent as nvarchar(10));
if (#SubComponentId is null)
set #cmd = #cmd +''',NULL,'''+#AssociatedTable +''')';
else
set #cmd = #cmd +''','''+cast(#SubComponentId as nvarchar(10))+''','''+#AssociatedTable +''');';
print (#cmd)
exec (#cmd)
set #Id=SCOPE_IDENTITY();
print (#Id)
END
Can anybody help me out resolve this issue
Thanks for sharing your valuable time.
Column name set in stored procedure but not working. But when I run this script empty rows appears. What I do this for run this script?
Create Procedure Test
()
AS
BEGIN
Declare #columnName nvarchar(50);
set #columnName ='StoreName';
SELECT *
FROM testtable
WHERE #columnName = 'storemanager'
END
You need to use dynamic SQL because you can't reference a column with a variable - T-SQL just doesn't parse things in that order. Try something like:
CREATE PROCEDURE dbo.Test
#columnName NVARCHAR(50),
#value NVARCHAR(4000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SELECT * FROM dbo.testtable WHERE '
+ QUOTENAME(#columnName) + ' = #value;';
EXEC sp_executesql #sql, N'#value NVARCHAR(4000)', #value;
END
GO
QUOTENAME() wraps the column in [square brackets] and hopefully protects you from SQL injection. You should also read these posts:
Bad habits to kick : using SELECT * / omitting the column list
Bad habits to kick : avoiding the schema prefix
My stored procedure "best practices" checklist