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