how to pass column name with parameter in insert sql statment

房东的猫 提交于 2019-12-02 05:15:47

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!