You're using string concatenation to build the dynamic SQL query. That leaves your code open to
SQL Injection[
^].
You need to pass the parameters as parameters instead of concatenating their values into the query.
Unfortunately you can't do that for the table name. Instead, you'll need to validate that the passed name is a valid table name.
You'll also want to be able to pass the values to insert into your stored procedure.
ALTER PROCEDURE spinserttable
@tname sysname,
@iname varchar(50),
@quantity int
As
BEGIN
DECLARE @SchemaName sysname, @TableName sysname;
DECLARE @sql nvarchar(max);
DECLARE @params nvarchar(100);
SET NOCOUNT ON;
SELECT
@SchemaName = S.name,
@TableName = T.name
FROM
sys.tables As T
INNER JOIN sys.schemas As S
ON S.schema_id = T.schema_id
WHERE
T.name = @tname
;
If @@ROWCOUNT = 0 RAISERROR('Invalid table name: %s', 16, 1, @tname);
SET @sql = N'INSERT INTO ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName) + N' (iname, quantity) VALUES (@iname, @quantity)';
SET @params = N'@iname varchar(50), @quantity int';
EXECUTE sp_executesql @sql, @params, @iname, @quantity;
END