是的,您可以这样做。事实上,微软在其系统存储过程中做到了这一点。您可以查找它们并查看该代码。另外,我过去做过类似的事情,但要创建一个存储过程,而不是一个表。思路基本一样,可以参考我的代码。
CREATE procedure [dbo].[ScriptAbm]
@tabla varchar(50)
AS
set nocount on
if object_id(@tabla) is null begin
select 'no existe la tabla'
return
end
select identity(int, 1,1) as idcolumna, c.name AS Columna, t.name AS Tipo,
case when t.name in ('varchar', 'char') then cast(c.length as varchar)
else null end as Longitud, ',' as coma
into #t
from syscolumns c
inner join systypes t on c.xtype = t.xtype
where c.id = object_id(@tabla)
declare @max int
select @max = max(idcolumna) from #t
update #t set coma = '' where idcolumna = @max
select texto from (
select 0 as orden, 1 idcolumna, 'CREATE PROCEDURE Actualizar' + @tabla texto
union
select 1, idcolumna, '@' + columna + ' ' + tipo
+ case when longitud is not null then ' (' + longitud + ')' else '' end
+ coma
from #t
union
select 2, 1, 'AS'
union
select 3, 1,
CHAR(13) + CHAR(10) +
'-- =================================================================' +
CHAR(13) + CHAR(10) +
'-- Fecha: ' + convert(varchar, getdate(), 103) +
CHAR(13) + CHAR(10) +
'-- Autor: Leonardo Arias Paz ' +
CHAR(13) + CHAR(10) +
'-- Descripción: Alta y modificación de la tabla ' + @tabla +
CHAR(13) + CHAR(10) +
'-- =================================================================' +
CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
union
select 3 as orden, 1, 'SET NOCOUNT ON' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
union
select 3, 2, 'IF @' + (SELECT columna from #t where idcolumna = 1) + ' = 0 BEGIN'
union
select 4, 1, char(9) + char(9) + 'INSERT INTO ' + @tabla + ' ('
union
select 5, idcolumna, char(9) + char(9) + char(9) + columna + coma
from #t
union
select 6, 1, char(9) + char(9) + ')'
union
select 7, 1, char(9) + char(9) + 'VALUES ('
union
select 8, idcolumna, char(9) + char(9) + char(9) + '@' + columna + coma
from #t
union
select 9, 1, char(9) + char(9) + ')'
union
select 9, 2, 'END ELSE BEGIN'
union
select 9, 3, char(9) + char(9) + 'UPDATE ' + @tabla + ' SET '
union
select 10, idcolumna, char(9) + char(9) + char(9) + columna + char(9) + ' = @' + columna + coma
from #t
where idcolumna > 1
union
select 11, idcolumna, char(9) + char(9) + 'WHERE ' + columna + ' = ' + '@' + columna
from #t
where idcolumna = 1
union
select 12, 1, 'END'
union
select 13, 1, CHAR(13) + CHAR(10) + 'SET NOCOUNT OFF'
union
select 13, 2, CHAR(13) + CHAR(10) + 'GO'
) q
order by orden, idcolumna
set nocount off
注意:
当我有我需要的所有代码时,我将其打印出来,你应该使用
EXEC sp_executesql @code
其中@code 是一个nvarchar 变量,用于存储您生成的代码。