日期:2014-05-17 浏览次数:20876 次
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([ID] INT,[class] VARCHAR(2),[status] VARCHAR(1))
INSERT [tb]
SELECT 1,'aa','F' UNION ALL
SELECT 1,'bb','S' UNION ALL
SELECT 1,'cc','D'
--------------开始查询--------------------------
SELECT * FROM [tb] PIVOT(MAX([status]) FOR [class] IN([aa],[bb],[cc])) as pit
----------------结果----------------------------
/*
ID aa bb cc
1 F S D
*/
------解决方案--------------------
DECLARE @t1 table
(
id int,
class varchar(50),
[status] varchar(50)
)
INSERT INTO @t1
SELECT 1,'aa','F'
UNION
SELECT 1,'bb','S'
UNION
SELECT 1,'cc','D'
SELECT
MAX(CASE WHEN class = 'aa' THEN [status] ELSE NULL END) 'aa',
MAX(CASE WHEN class = 'bb' THEN [status] ELSE NULL END) 'bb',
MAX(CASE WHEN class = 'cc' THEN [status] ELSE NULL END) 'cc'
FROM @t1
行列转换,动态拼接SQL,拼接SQL时应该使用临时表,拼接SQL中的表变量无法和外面交互
------解决方案--------------------
--一次只插入一行,可以用下面的触发器,需要用动态sql
alter TRIGGER tinsert_test1 ON [dbo].[test1]
FOR INSERT
AS
begin
declare @sql varchar(200)
declare @col_name varchar(20)
declare @id int
declare @status varchar(10)
--存在相同id更新
if exists(select 1 from test2,inserted where test2.id = inserted.id )
begin
select @col_name = class,@id = id,@status = status from inserted
select @sql = 'update test2 set ' + @col_name+' = '''+@status+''' where id = '+cast(@id as varchar) + ''
exec(@sql)
end
else
begin
select @col_name = class,@id = id,@status = status from inserted
--没有相同id先插入id
insert into test2(id)
select id
from inserted
--再更新值
select @col_name = class,@id = id,@status = status from inserted
select @sql = 'update test2 set ' + @col_name+' = '''+@status+''' where id = '+cast(@id as varchar) + ''
exec(@sql)
end
end