2013-04-25 162 views
1

我有兩種類型的表組織OrgLogin。使用連接連接兩個或多個表

組織:

ID 
Name 

OrgLogin:

LoginId 
UserName 
Password 

我想和組織中的表的用戶名和密碼選擇查詢。所以我使用了聯接。

我的查詢,

select top(55)'Insert into Organizations(Id,Username,Password,Name)values(' + 
     Cast(o.organizationId as varchar(50))+',''' + 
     IsNull(''''+ol.UserName+'''', 'NULL')+','+ 
     isnull(convert(nvarchar(max),HASHBYTES('MD5',ol.Password),1),'NULL')+ ')' 
    FROM Organization AS o 
    left join OrgLogin As ol ON ol.LoginId=o.OrganizationID 

我有以下結果集,

Insert into Organizations(Id,CreateDate,Username,Password)values(1,'NULL,NULL) 

Insert into Organizations(Id,CreateDate,Username,Password)values(2,'NULL,NULL) 

Insert into Organizations(Id,CreateDate,Username,Password)values(3,'NULL,NULL) 

Insert into Organizations(Id,CreateDate,Username,Password)values(4,'NULL,NULL) 

Insert into Organizations(Id,CreateDate,Username,Password)values(5,''V EX Electronics Systems Pvt.Ltd.Chennai',0xACB3BB721E1EC47C4CB569331ACC4E8E) 

Insert into Organizations(Id,CreateDate,Username,Password)values(5,''V EX Electronics Systems Pvt.Ltd.Chennai',0xACB3BB721E1EC47C4CB569331ACC4E8E) 

ID是重複看到 '5' 標識。兩次創建。爲什麼它發生?任何想法?

回答

0

你應該整理一下單引號(第一ISNULL之前)

select top(55)' 
    Insert into Organizations(Id,Username,Password,Name)values(' + 
    Cast(o.organizationId as varchar(50))+',' + 
    IsNull(''''+ol.UserName+'''', 'NULL')+','+ 
    isnull(convert(nvarchar(max),HASHBYTES('MD5',ol.Password),1),'NULL')+ ')' 
FROM Organization AS o 
left join OrgLogin As ol ON ol.LoginId=o.OrganizationID 

接下來,o.id會重複每當有該組織多個OrgLogin記錄。

+0

所以如何避免o.id不應該重複。因爲Organizationid是唯一的。 – PoliDev 2013-04-25 06:37:25