你想要得到的SQL語句:
DECLARE @tb TABLE(PicklistTable VARCHAR(30),PicklistColumnName VARCHAR(30),FormTable VARCHAR(30),FormColumnName VARCHAR(30))
INSERT INTO @tb(PicklistTable,PicklistColumnName,FormTable,FormColumnName)
SELECT 'tblEthnicityValues','Ethnicity_ID','tblContact','Contact_Ethnicity_ID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAC','FatherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAC','MotherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAYP','EthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAYP','FatherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACIHAYP','MotherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACRHAC','FatherEthnicityID' UNION
SELECT 'tblEthnicityValues','Ethnicity_ID','udfOHFTCYPLACRHAC','MotherEthnicityID'
DECLARE @sql VARCHAR(max)
SELECT @sql='SELECT '+t.PicklistColumnName+',(0'+t.subCountSQL+') AS'+CHAR(13)+'Count FROM '+t.PicklistTable+CHAR(13)+t.subSQL FROM (
SELECT DISTINCT PicklistTable,PicklistColumnName,t2.* ,t3.*
FROM @tb AS t1
CROSS APPLY(SELECT 'INNER JOIN '+FormTable+' ON PicklistColumnName='+tt.FormTable+'.'+tt.FormColumnName+' '
FROM @tb AS tt WHERE tt.PicklistTable=t1.PicklistTable AND tt.PicklistColumnName=t1.PicklistColumnName
FOR XML PATH('')
) AS t2(subSQL)
CROSS APPLY(SELECT '+COUNT('+tt.FormTable+'.'+tt.FormColumnName +')'
FROM @tb AS tt WHERE tt.PicklistTable=t1.PicklistTable AND tt.PicklistColumnName=t1.PicklistColumnName
FOR XML PATH('')
) AS t3(subCountSQL)
)AS t
PRINT @sql
EXEC(@SQL)
變量@SQL將是:
SELECT Ethnicity_ID,(0+COUNT(tblContact.Contact_Ethnicity_ID)+COUNT(udfOHFTCYPLACIHAC.FatherEthnicityID)+COUNT(udfOHFTCYPLACIHAC.MotherEthnicityID)+COUNT(udfOHFTCYPLACIHAYP.EthnicityID)+COUNT(udfOHFTCYPLACIHAYP.FatherEthnicityID)+COUNT(udfOHFTCYPLACIHAYP.MotherEthnicityID)+COUNT(udfOHFTCYPLACRHAC.FatherEthnicityID)+COUNT(udfOHFTCYPLACRHAC.MotherEthnicityID)) AS Count FROM tblEthnicityValues
INNER JOIN tblContact ON PicklistColumnName=tblContact.Contact_Ethnicity_ID INNER JOIN udfOHFTCYPLACIHAC ON PicklistColumnName=udfOHFTCYPLACIHAC.FatherEthnicityID INNER JOIN udfOHFTCYPLACIHAC ON PicklistColumnName=udfOHFTCYPLACIHAC.MotherEthnicityID INNER JOIN udfOHFTCYPLACIHAYP ON PicklistColumnName=udfOHFTCYPLACIHAYP.EthnicityID INNER JOIN udfOHFTCYPLACIHAYP ON PicklistColumnName=udfOHFTCYPLACIHAYP.FatherEthnicityID INNER JOIN udfOHFTCYPLACIHAYP ON PicklistColumnName=udfOHFTCYPLACIHAYP.MotherEthnicityID INNER JOIN udfOHFTCYPLACRHAC ON PicklistColumnName=udfOHFTCYPLACRHAC.FatherEthnicityID INNER JOIN udfOHFTCYPLACRHAC ON PicklistColumnName=udfOHFTCYPLACRHAC.MotherEthnicityID
這聽起來像一個很可怕的設計。你已經設計了自己被迫使用動態sql的一切。這幾乎違背了使用關係數據庫的觀點。如果你真的想在這裏得到一些幫助是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –
是的,恐怕這個設計不會帶你到你身邊想去。你只是不想在動態SQL中這樣做。如果您可以選擇重新設計數據庫結構,請這樣做。 – criticalfix
不幸的是,我不能做任何與數據庫...這聽起來不太有希望...... :( –