答案 0 :(得分:0)
你可以这样做,我没有睾丸希望它会起作用;)
create table #Result (
ID nvarchar(10),
[Date] datetime,
[DrugIndex] int,
Drug1 nvarchar(1000))
DECLARE @ID nvarchar(10),
@Date datetime,
@Drug nvarchar(1000)
DECLARE crResult CURSOR FOR SELECT ID,[Date],[Drug] FROM tblSource
OPEN crResult
FETCH NEXT FROM crResult INTO @ID,@Date,@Drug
WHILE @@FETCH_STATUS=0
BEGIN
IF EXISTS(SELECT * FROM #Result WHERE ID=@ID AND [Date]=@Date)
BEGIN
DECLARE @Index int
SET @Index=(SELECT DrugIndex FROM #Result WHERE Id=@Id and [Date]=@Date)
SET @Index=@Index+1
DECLARE @sqlCmd nvarchar(1024)
SET @sqlCmd='ALTER TABLE #Result ADD Drug'+CONVERT(nvarchar(10),@Index)+' nvarchar(1000)'
EXECUTE (@sqlCmd)
SET @sqlCmd='UPDATE #Result SET [DrugIndex]='+CONVERT(nvarchar(10),@Index)+', [Drug'+CONVERT(nvarchar(10),@Index)+
']='''+@Drug+''' WHERE ID='+CONVERT(nvarchar(10),@ID)+''' AND [Date]='''+CONVERT(nvarchar(20),@Date)+''''
EXECUTE (@sqlCmd)
END
ELSE
INSERT INTO #Result(ID,[Date],DrugIndex,[Drug1]) VALUES @ID,@Date,1,@Drug
FETCH NEXT FROM crResult INTO @ID,@Date,@Drug
END
CLOSE crResult
DEALLOCATE crResult