首页  编辑  

动态执行SQL语句

Tags: /超级猛料/Database.数据库相关/SQL Server/   Date Created:
SQL Server中利用EXEC动态执行SQL语句
Kingron, 2007
EXEC可以调用存储过程,也可以调用一个SQL字符串语句!下面的例子演示了如何来做:
CREATE PROCEDURE MyInit
  @sTable VARCHAR(100),
  @sFields VARCHAR(512),
  @sValues VARCHAR(1024)
AS
DECLARE @sSQL VARCHAR(4096)
SET @sSQL = 'INSERT INTO ' + @sTable + ' (' + @sFields  + ') VALUES(' + @sValues + ')'
EXEC (@sSQL)
GO
DECLARE @sTable VARCHAR(50)
DECLARE @sField VARCHAR(255)
SET @sTable = 'myTable'
SET @sField = 'id, Name, Value1, Value2, Value3'
EXEC MyInit @sTable, @sField, '0, '''', 0, 0, -1' -- 默认
EXEC MyInit @sTable, @sField, '1, ''Test1'', 505, 02, 0'
EXEC MyInit @sTable, @sField, '2, ''Test2'', 505, 01, 0'
........
DROP PROCEDURE MyInit
GO