2012-08-16 82 views
0

對不起,這個愚蠢的問題,但我是相當新的SQL,我試圖做一些非常簡單的事情。我創建了一個由3個表格組成的視圖,它完美地工作。不過,我需要一些字段來使用某種形式的格式。我正在使用SQL Server Management Studio GUI來創建此視圖。格式化SQL Server數據庫視圖中的數據

我在視圖2列需要驗證:GenderDOB

性別包含任一「M」,「F」或空白,我需要在視圖中改變這個輸出'Male''Female'

DOB包含一個未格式化的日期字符串,我需要將其格式化爲DD/MM/YYYY

我應該在哪裏創建這個驗證,奠定了我所有的卡在桌子上的利益這裏是創建視圖腳本:

CREATE VIEW [dbo].[PMIPatient] 
AS 
    SELECT  
     dbo.refPasPatientRec8Master.Patient_Internal_number AS HospitalNumber, 
     dbo.refPasPatientRec1Master.[H+C_Number] AS NHSNumber, 
     dbo.refPasPatientRec1Master.Patient_Title AS Salutation, 
     dbo.refPasPatientRec1Master.Surname, 
     dbo.refPasPatientRec1Master.Forenames AS Forename, 
     dbo.refPasPatientRec1Master.Sex_Code AS Gender, 
     dbo.refPasPatientRec1Master.Date_of_Birth AS Dob, 
     dbo.refPasPatientRec1Master.Date_of_Death AS Dod, 
     dbo.refPasPatientRec1Master.Address_Line_1 AS Address1, 
     dbo.refPasPatientRec1Master.Address_Line_2 AS Address2, 
     dbo.refPasPatientRec1Master.Address_Line_3 AS Address3, 
     dbo.refPasPatientRec1Master.Address_Line_4 AS Address4, 
     dbo.refPasPatientRec1Master.[Postcode/Pseudo_postcode] AS Postcode, 
     dbo.refPasPatientRec8Master.Patients_Phone_Number AS Telephone1, 
     dbo.refPasPatientRec39Master.Work_Telephone_Number AS Telephone2, 
     dbo.refPasPatientRec1Master.GP_Code AS GPGMCode, 
     dbo.refPasPatientRec1Master.Death_Indicator AS deceasedFlag 
FROM   
     dbo.refPasPatientRec1Master 
INNER JOIN 
     dbo.refPasPatientRec39Master ON dbo.refPasPatientRec1Master.Patient_Internal_number = dbo.refPasPatientRec39Master.Patient_Internal_number 
INNER JOIN 
     dbo.refPasPatientRec8Master ON dbo.refPasPatientRec1Master.Patient_Internal_number = dbo.refPasPatientRec8Master.Patient_Internal_number 
+1

你要求'驗證'或'格式'?例如; 「驗證」將檢查性別值是否爲「狗」並告訴您存在問題。或者您可以確定數據中只存在允許的值嗎? – MatBailie 2012-08-16 11:01:58

+0

道歉格式化!我現在編輯 – Bradley 2012-08-16 11:03:42

回答

2

這一切都是假設你使用MS-SQL!

要更改您的Sex_Code的返回值,請使用CASE聲明。有關更多信息,請參閱this link

更改此:

dbo.refPasPatientRec1Master.Sex_Code AS Gender 

要這樣:

CASE dbo.refPasPatientRec1Master.Sex_Code 
    WHEN 'M' THEN 'Male' 
    WHEN 'F' THEN 'Female' 
    ELSE 'Unknown' 
END AS Gender 

要格式化DATE_OF_BIRTH值然後使用CONVERT方法將其與指定的樣式(103參數)轉換爲NVARCHAR。有關更多詳細信息,請參閱this link

更改此:

dbo.refPasPatientRec1Master.Date_of_Birth AS Dob 

要:

CONVERT(NVARCHAR(10), dbo.refPasPatientRec1Master.Date_of_Birth, 103) AS Dob 
1

使用CASE表達式中的性別轉換成你想要的格式。

使用CONVERT功能與適當的字符格式號的日期轉換爲具體的數字,這樣的:

SELECT CONVERT(varchar(8), dbo.refPasPatientRec1Master.Date_of_Birth, 112) 

我不知道你的「SQL Management Studio中」是否讓您編輯個人選擇列表達式雖然...