Correct posture for SQL dynamic add field

Source: Internet
Author: User

How do I add fields to a specified table dynamically?

First, create a table "Tbl_autofileds"

(tablename table name, fieldname field name, datatype data type, length isnull if NULL is allowed)

Second, create a table trigger for "tbl_autofileds"

SETAnsi_nulls Ongoset QUOTED_IDENTIFIER Ongo
-- =============================================--author:< Author >--Create Date: <20160320 date,,>--description:< adding columns to the corresponding table when the table is inserting data >
-- =============================================ALTER TRIGGER [dbo].[Filed_auto] on [dbo].[tbl_autofileds] for Insert as DECLARE@tb_Name varchar( -), @coloun varchar( -),@datatype varchar( -),@length varchar( +),@isnull varchar(Ten),@sql varchar( $) Beginset NOCOUNT on; Select @tb_Name=Tabld_name,@coloun=FieldName,@datatype=DataType@length=[length],@isnull=[IsNull] frominsertedif not exists(Select * fromsyscolumnswhereId=object_id(@tb_Name) andName=@coloun) begin Set @sql='ALTER Table'+@tb_Name+'Add'+@coloun+' '+@datatype+'('+@length+') '+@isnullexec(@sql) End


Third, add content to the table, while adding columns to the corresponding table

Inserting content into the Tbl_autofields table triggers a trigger to dynamically add fields to the specified table:

Insert  into Values ('tbl_test','MyField','nvarchar  ','+ ','null');

We added a field myfield with a data type of nvarchar (200) to the Tbl_test table.

Recommended Technical class public number: Codel

Correct posture for SQL dynamic add field

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.