2017-10-18 143 views
0

我有這樣的SPSQL複製多個記錄時生成唯一的ID

CREATE PROCEDURE ApplyExistingImageAcrossModel 
@capidfrom int, 
@capidto int, 
@type int 
AS 
BEGIN 

DECLARE @imageid uniqueidentifier 

INSERT INTO ImageMetaData 
(ImageId,CapId,[Type],Source,DateAdded,OriginalFileName,OriginalUrl,isDefault,Height,Width,ViewType,CapImageId,islive) 
SELECT @imageid,@capidto,@type,source,GETDATE(),originalfilename,originalurl,isdefault,height,width,viewtype,capimageid,islive 
FROM ImageMetaData 
WHERE [type] = @type AND capid = @capidfrom 

INSERT INTO ImageData 
(ImageId,ImageBinary) 
SELECT @imageid,ImageBinary 
FROM ImageData A 
LEFT JOIN ImageMetaData B 
ON A.ImageId = B.ImageId 
WHERE B.[type] = @type 
AND B.capid = @capidfrom 

END 

的問題是,選擇可以爲特定的capid返回多個記錄,我想複製它們,但每個記錄都需要一個獨特的@imageid,我只生成一次,我需要在兩個表中使用imageid

感謝

+0

我不確定它是否是重複的 - 如果是這樣,請讓我知道:https://stackoverflow.com/a/34832231/3094533 –

+1

我會建議使用比A,B更好的別名。http: //sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-table-aliases-like-abc-or-t1-t2-t3.aspx您是否考慮過使用你最初插入的OUTPUT子句? https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql –

回答

0

而不是創建一個變量,聲明表變量來存儲唯一的ID。然後,使用OUPUT子句記錄所有ID。事情是這樣的:

DECLARE @DataSource TABLE 
(
    @imageid uniqueidentifier 
); 

INSERT INTO ImageMetaData(ImageId,CapId,[Type],Source,DateAdded,OriginalFileName,OriginalUrl,isDefault,Height,Width,ViewType,CapImageId,islive) 
OUTPUT inserted.ImageId 
INTO @DataSource (@imageid) 
SELECT NEWID(),@capidto,@type,source,GETDATE(),originalfilename,originalurl,isdefault,height,width,viewtype,capimageid,islive 
FROM ImageMetaData 
WHERE [type] = @type AND capid = @capidfrom 

現在,在@DataSource表我們有插入imageID秒。不管你想要什麼,都要和他們一起做