开发者

how to pass column name with parameter in insert sql statment

how to pass column name with parameter in insert sql statment e.g.

@name='n开发者_JS百科ame'
insert into employees (id,@name) values(1,'a')

is this possible?


No it isn't possible you would need to build the SQL Statement including the column either in your application or by using dynamic SQL in SQL Server itself.

Edit: RE: "what's dynamic sql". The approach is as follows.

DECLARE @Value nvarchar(100)
DECLARE @InsertString nvarchar(1000)
DECLARE @name sysname

SET @name ='name'
SET @Value = 'a'

SET @InsertString= 'INSERT INTO EMPLOYEES (id,' + @name + ') values(1, @Value)'


EXEC sp_executesql @InsertString, N'@Value nvarchar(100)', @Value 

However there are 2 issues with it. First @name must be SQL Injection proof. For the same reason you would also want to use a parameter for @Value. However the data type for that must be specified in advance meaning that it won't be suitable for all columns. So on reflection you would be better off doing this in your application layer. (NB: The same considerations about SQL injection still apply and your application code will need to add the parameter of the correct type for the column)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜