I have 2 tables to manage generate real table with table name and column:
Table:
TableID TableName
----------------------
1 TopCity
TableColumn:
ColumnID ColumnName DataType Size
-------------------------------------------
1 CityID int null
2 CityName nvarchar 100
I want to write a procedure to create real table TopCity (CityID, CityName) with column
details as described in TableColumn.
CREATE TABLE TopCity
(
CityID INT IDENTITY(1,1),
CityName NVARCHAR(100)
)
This is solution
CREATE PROC AUTOGEN_TABLE
@BangID int AS DECLARE @DanhSachTruong VARCHAR(1000), @TenBang VARCHAR(100) -- ,@i INT = 1, @j INT = 0 --SELECT @j = COUNT(*) FROM BANG_DULIEU --WHILE @i <= @j BEGIN SELECT @TenBang = B.TenBang FROM BANG_DULIEU B WHERE BangID = @BangID SELECT @DanhSachTruong = COALESCE(@DanhSachTruong + ', ', '') + '' + tc.TenTruong + ' ' + tc.KieuDuLieu + '' + CASE WHEN tc.DoRong IS NULL THEN '' ELSE CONCAT('(',CAST(tc.DoRong AS VARCHAR),')') END + CASE WHEN RIGHT(tc.TenTruong,2)='ID' THEN ' IDENTITY(1,1)' ELSE '' END FROM BANG_DULIEU t INNER JOIN TRUONG_DULIEU tc ON tc.BangID = t.BangID WHERE t.TenBang = @TenBang --SELECT @TenBang, @DanhSachTruong EXEC('CREATE TABLE ' + @TenBang + ' ( ' + @DanhSachTruong + ' )') --SET @i = @i + 1 END |
Thứ Năm, 11 tháng 1, 2018
Generate table with define SQL Server
Đăng ký:
Đăng Nhận xét (Atom)
Không có nhận xét nào:
Đăng nhận xét