Here is a 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 have I changed?
- Always use the prefix
dbowhen creating / referencing objects. - The names of tables and columns
NVARCHARcan be longer than 150 characters. It is much safer to allow parameters to place a table that someone can add in the future. SET NOCOUNT ON .@sql NVARCHAR.QUOTENAME , , SQL-, (, ).- (-, SQL-, ).