Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I want a dynamic insert query for insert data in table, I have 5 tables which have same column want a single query to insert data into tables.

I create sp


SQL
create proc insertdata
(
@tableName nvarchar(50),
@name nvarchar(50),
@Nrange nvarchar(50),
@isActive bit
)
as 
begin

declare @sql nvarchar(200)
set @sql = 'isert into '+@tableName +' values('+@name +','+@Nrange +','+@isActive +')';
exec(@sql)
end


like this but when try to execute it throws error


ERROR
------------
C#
Msg 402, Level 16, State 1, Procedure insertdata, Line 15
The data types nvarchar and bit are incompatible in the add operator.
Posted
Updated 25-Feb-16 8:57am
Comments
aarif moh shaikh 6-Jan-16 6:12am    
check your insert spelling.

A perfect example of why stored procedures don't automatically protect you from SQL Injection[^]!

Use sp_executesql[^] to execute your query, passing the parameters as parameters. You also need to validate that the table name is a valid table in the current database.
SQL
CREATE PROC insertdata
(
    @tableName nvarchar(50),
    @name nvarchar(50),
    @Nrange nvarchar(50),
    @isActive bit
)
As 
BEGIN
DECLARE @sql nvarchar(max);
DECLARE @RealTableName sysname;
    
    SET NOCOUNT ON;
    
    SELECT
        @RealTableName = QUOTENAME(s.name) + '.' + QUOTENAME(t.name)
    FROM
        sys.tables As T
        INNER JOIN sys.schemas As S
        ON S.schema_id = T.schema_id
    WHERE
        T.name = @tableName
    ;
    
    If @@ROWCOUNT = 0 RAISERROR('Invalid table: "%s"', 16, 1, @tableName);

    SET @sql = N'INSERT INTO ' + @RealTableName + N' VALUES (@name, @Nrange, @isActive)';
    
    EXEC sp_executesql @sql, 
        N'@name nvarchar(50), @Nrange nvarchar(50), @isActive bit',
        @name = @name,
        @Nrange = @Nrange,
        @isActive = @isActive
    ;
END



Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
 
Share this answer
 
Your parameter @isActive is of type bit while rest of the command is nvarchar. You cannot use + operator between these two data types. You might want to convert the bit parameter to nvarchar to get this working.
 
Share this answer
 
Comments
Dj@y 6-Jan-16 7:26am    
after change data type sp is created
But afetr exicution of sp got error
error-----
Msg 2812, Level 16, State 62, Procedure insertdata, Line 17
Could not find stored procedure 'insert into tbltest2(Name,Nrange,isActive) values(test,3 - 5,1)'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900