动态传给数据库一个以字段名组成的数组,怎样根据数组生成表格字段并创建表格?
数据格式如下:
t1;t2;t3;t4;t5;t6;t7;t8;t9;t10;t11;t12;t13;t14;
ps:字段名没有相似点,只用分号进行隔开
创建的字段类型都是NVARCHAR类型
数据库是sql2000或者2005 SQL 数据库 SQLSERVER
[解决办法]
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-08-13 14:12:23
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
--Jun 10 2013 20:09:10
--Copyright (c) Microsoft Corporation
--Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([a] varchar(46))
insert [huang]
select 't1;t2;t3;t4;t5;t6;t7;t8;t9;t10;t11;t12;t13;t14'
--------------开始查询--------------------------
select DISTINCT
SUBSTRING([a],number,CHARINDEX(';',[a]+';',number)-number) as [a]
from
[huang] a,master..spt_values
where
number >=1 and number<len([a])
and type='p'
and substring(';'+[a],number,1)=';'
----------------结果----------------------------
/*
a
----------------------------------------------
t1
t10
t11
t12
t13
t14
t2
t3
t4
t5
t6
t7
t8
t9
*/
DECLARE @fieldlist NVARCHAR(MAX), @createSql NVARCHAR(MAX)
SET @fieldlist = N't1;t2;t3;t4;t5;t6;t7;t8;t9;t10;t11;t12;t13;t14;'
SET @fieldlist = RTRIM(LTRIM(@fieldlist))
SET @createSql = 'CREATE TABLE dbo.Table_name (' + REPLACE(@fieldlist, ';', ' nvarchar(MAX), ')
SET @createSql = LEFT(@createSql, LEN(@createSql)-1) + ')'
--PRINT @createSql
EXEC(@createSql)