如何在声明的变量中添加结果

时间:2015-04-14 08:33:56

标签: sql-server sqlite

这是我的代码:

declare @var table(conz nvarchar(255))
declare @str nvarchar (255)
set @str = 'create table tempo( '
insert into @var
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = object_id('tablea')
select conz from @var
print @str

如何在声明的变量中添加结果?

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试根据系统表创建create table子句。这是我用过的:

select 
  c.name + ' ' + 
  t.name + 
  case 
    when t.name like '%char' then '(' + convert(varchar, c.max_length) + ')' 
    when t.name in ('decimal','numeric') then '(' + convert(varchar, c.precision) 
      + '.' + convert(varchar, c.scale) + ')' 
    else '' end +
  case when c.is_nullable = 1 then ' NULL' else ' NOT NULL' end
from 
  sys.columns c 
  join sys.types t 
    on c.system_type_id = t.system_type_id and c.user_type_id = t.user_type_id
where
    object_id = object_id('YOURTABLENAME')

它可能不包含所有数据类型,但至少它适用于所有基本类型。

答案 1 :(得分:0)

如果你想拥有一个变量,你需要像这样使用它。

DECLARE @str nvarchar (255)
SET @str = 'CREATE TABLE TEMPO ('

SELECT @str = @str + 
    '[' + c.name + '] [' + t.name + '] ' +
    CASE  
        WHEN t.name LIKE '%char' THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE convert(varchar, c.max_length)  END + ')' 
        WHEN t.name IN ('decimal','numeric') THEN '(' + convert(varchar, c.precision) + '.' + convert(varchar, c.scale) + ')' 
        ELSE '' 
    END +
    CASE 
        WHEN c.is_identity = 1 THEN 'IDENTITY(' +
            (SELECT convert(varchar, ic.seed_value) FROM sys.identity_columns ic WHERE c.column_id = ic.column_id)
            + ',' + 
            (SELECT convert(varchar, ic.increment_value) FROM sys.identity_columns ic WHERE c.column_id = ic.column_id)
            +')'
        ELSE ''
    END +
    CASE 
        WHEN c.is_nullable = 1 THEN ' NULL' 
        ELSE ' NOT NULL' 
    END + ','
FROM 
    sys.columns c 
    INNER JOIN 
    sys.types t on c.system_type_id = t.system_type_id And c.user_type_id = t.user_type_id
WHERE 
    c.[object_id] = OBJECT_ID('tablea')

PRINT @str
  

注意:
  我还为IDENTITY添加MAX并修改varchar值。