使用存储过程在SQL Server 2008中创建动态表 [英] Dynamic Table Creation in SQL Server 2008 using stored procedure

查看:112
本文介绍了使用存储过程在SQL Server 2008中创建动态表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用存储过程在sql server 2008中创建动态表创建

how to create dynamic table creation in sql server 2008 using stored procedure

推荐答案

如下所示:

How about something like:
CREATE PROCEDURE sproc_CreateTableAtRuntime
           @TableName NVARCHAR(128)
          ,@Column1Name NVARCHAR(32)
          ,@Column1DataType NVARCHAR(32)
          ,@Column1Nullable NVARCHAR(32)

AS

DECLARE @SQLString NVARCHAR(MAX)
SET @SQString = 'CREATE TABLE ' + @TableName + '( '+ @Column1Name + ' ' + @Column1DataType + ' '+ @Column1Nullable +') ON PRIMARY '

EXEC (@SQLString)



To执行:


To execute:

EXEC sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'





如果需要,类似的讨论此处。 [ ^ ]



此外,请参阅:如何使用SQLServer存储过程动态创建表 [ ^ ]





表可以通过以下方式动态创建。



1.动态SQL - '需要构建查询创建表'。

注意: - 在执行Dynamic sql查询之前,你必须检查表是否已经存在





2. SELECT语句



这里有两个创建表的选项。



a)创建表格和数据



Hi,

Tables can be created dynamically in following ways.

1. Dynamic SQL -- 'Need to construct query to create table'.
Note :- here you have to check whether the table is already there
or not before executing the Dynamic sql query.

2. SELECT statement

Here we have two options to create table.

a)Create table along with data

SELECT A.COL1,A.COL2... INTO NEWTABLE
         FROM EXISTINGTABLE





如果执行此查询... sql server不仅会根据SELECT条件创建一个表

而且还会将结果集

插入到新创建的表中。



b)仅使用架构创建表格





If you execute this query ... sql server not only creates a table
according to the SELECT criteria but also inserts the result set
of the query into the newly created table.

b)Create table with schema only

SELECT A.COL1,A.COL2... INTO NEWTABLE
FROM EXISTINGTABLE WHERE 1=0



此查询根据SELECT条件创建表。这里

数据不会存储在新创建的表中。



谢谢


This query creates table according to the SELECT criteria. Here
data will not be stored in newly created table.

Thank you


U应该试试这样:



U should try like that :

ALTER PROCEDURE spName(
DECLARE @tableName VARCHAR(100),@columnName VARCHAR(50),@Query VARCHAR(8000) )
BEGIN
SET @Query='CREATE TABLE '  + @tableName + '(' +@columnName + ' VARCHAR(200)'+ ')'
EXECUTE (@Query)
END


这篇关于使用存储过程在SQL Server 2008中创建动态表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆