This procedure has three parameters. But when I try to execute by passing parameters it shows me an error. Please help me.
create procedure queryfunctions @Tabname varchar(150),@colname varchar(150),@valuesname varchar(150)
as
begin
declare @sql varchar(4000)
select @sql='select * from @Tabname where @colname=@valuesname'
exec(@sql)
end
exec queryfunctions 'education','eduChildName','Revathi'
Error :
Msg 1087, Level 15, State 2, Line 1 Must declare the table variable "@Tabname".
Using CTEs, for instance, you can use SELECT from <subquery> in Open SQL. In my case I needed to execute dynamic SELECT count( DISTINCT col1, col2, …) which is not possible in the regular OpenSQL.
Native dynamic SQL only supports a RETURNING clause if a single row is returned. See Also: "Performing DML with RETURNING Clause Using Dynamic SQL: Example" for examples of DBMS_SQL package code and native dynamic SQL code that uses a RETURNING clause.
Here is a much safer alternative:
ALTER PROCEDURE dbo.queryfunctions
@Tabname NVARCHAR(511),
@colname NVARCHAR(128),
@valuesname VARCHAR(150)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX);
SET @sql = 'SELECT * FROM ' + @Tabname
+ ' WHERE ' + QUOTENAME(@colname) + ' = @v';
EXEC sp_executesql @sql, N'@v VARCHAR(150)', @valuesname;
END
GO
EXEC dbo.queryfunctions N'dbo.education', N'eduChildName', 'Revathi';
What did I change?
dbo
prefix when creating / referencing objects.NVARCHAR
and can be longer than 150 characters. Much safer to allow the parameters to accommodate a table someone might add in the future.SET NOCOUNT ON
as a guard against network overhead and potentially sending erroneous result sets to client.@sql
should always be NVARCHAR
.QUOTENAME
around entity names such as tables or columns to help thwart SQL injection and also to guard against poorly chosen names (e.g. keywords).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With