日期:2014-05-18  浏览次数:20620 次

存储过程动态创建表
CREATE PROCEDURE cp_ttt
(
@tableSponsor nvarchar(20)
)
 AS

declare @sqlTableCreate nvarchar(200)

set @sqlTableCreate = N' Create @tableName
( orgID nchar (10), 
orgRegSubject nchar (10), 
subjectTitle nvarchar (10),
subjectSummary nvarchar (10) 
) '
execute sp_executesql @sqlTableCreate, 
N'@tableName nvarchar(20)',
@tableSponsor
GO

查询分析器调试,总是出现问题
服务器: 消息 170,级别 15,状态 1,行 1
[Microsoft][ODBC SQL Server Driver][SQL Server]第 1 行: '@tableName' 附近有语法错误。


------解决方案--------------------
SQL code
alter PROCEDURE cp_ttt 
( 
@tableSponsor nvarchar(20) 
) 
 AS 

declare @sqlTableCreate nvarchar(1000) 


set @sqlTableCreate = N'Create  table '+@tableSponsor+'
 (orgID nchar  (10),  
orgRegSubject nchar (10),  
subjectTitle nvarchar (10), 
subjectSummary nvarchar (10))' 

execute    @sqlTableCreate

------解决方案--------------------
@tableSponsor 是干啥了,没用?
@tableName 没定义.

SQL code
CREATE PROCEDURE cp_ttt @tableSponsor nvarchar(20)  
AS 
begin
  declare @sqlTableCreate nvarchar(200) 
  declare @tablename as varchar(10)
  set @tablename = '...' -- or set @tablename = @tableSponsor 
  set @sqlTableCreate = N'Create table ' + @tableName +
  '(orgID nchar  (10),  
  orgRegSubject nchar (10),  
  subjectTitle nvarchar (10), 
  subjectSummary nvarchar (10)  
  )'
  exec(@sqlTableCreate)
end 
go

------解决方案--------------------
SQL code
CREATE PROCEDURE cp_ttt 
(
@tableSponsor nvarchar(20)
)
AS

declare @sqlTableCreate nvarchar(1000)


set @sqlTableCreate = N'Create  table '+@tableSponsor+N'
(orgID nchar  (10), 
orgRegSubject nchar (10), 
subjectTitle nvarchar (10),
subjectSummary nvarchar (10))'
execute  sp_executesql  @sqlTableCreate

GO
----
EXEC cp_ttt N'QQQ'
DROP TABLE QQQ

------解决方案--------------------
SQL code
CREATE PROCEDURE cp_ttt
(
@tableSponsor nvarchar(20)
)
 AS

declare @sqlTableCreate nvarchar(1000) 


set @sqlTableCreate = N'Create  table '+@tableSponsor+N'
 (orgID nchar  (10),  
orgRegSubject nchar (10),  
subjectTitle nvarchar (10), 
subjectSummary nvarchar (10))' 
execute  sp_executesql  @sqlTableCreate

GO 





----测试存储过程
EXEC cp_ttt N'QQQ'
DROP TABLE QQQ

------解决方案--------------------
探讨
引用:
引用:
大家都是给的用 exec 方法来实现的
我想要用
execute sp_executesql @sqlTableCreate,
N'@tableName nvarchar(20)',
@tableSponsor
这个方法来实现


不都是sp_executesql 吗
你写的sp_executesql方法,参数有问题



那咋写才正确呢?
帮忙写一下吧