create procedure addColumn(@value varchar(150),@id varchar(20)) as
begin
Declare @max_column varchar(30)
Declare @column_name varchar(30)
Declare @sql varchar(150)
Declare @sql_update varchar(250)
select @max_column = max(Column_name)from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='TableA'
set @column_name = 'remark'+cast(isnull(replace(@max_column,'remark',''),0)+1 as varchar(15)) --หา Column
--print @column_name;
set @sql = 'alter Table TableA add '+@column_name+' varchar(150)' --สร้าง Column
exec( @sql)
set @sql_update = 'update TableA set '+@column_name+' = '''+@value+''' where id='+@id+'' -- update ยัดเข้าไป
exec( @sql_update)
end;
อันนี้เวลาเรียกใช้
Code (SQL)
execute addColumn 'TEST','1'
Date :
2015-04-24 10:03:01
By :
ipstarone
No. 11
Guest
Code (SQL)
CREATE FUNCTION [dbo].[fn_RemarkList_By_ContractNo](@ContractNo VARCHAR(20))
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE
@RemarkList VARCHAR(MAX)
SELECT @RemarkList =
COALESCE(@RemarkList + ';', '') +
Remark
FROM Table
WHERE [Contract No] = @ContractNo
RETURN @RemarkList
END
GO
SELECT [Contract No], dbo.fn_RemarkList_By_ContractNo]([Contract No]) AS Remarks
FROM Handle