2016-11-10 62 views
0

我在這裏有一個挑戰,我有一個表叫fileTable有以下欄目:返回兩個項目的字段和值從SQL Server功能

FileID FileName 
    ================= 
     1 | sdk 
     2 | mdk 
     3 | jdk 
     4 | apk 

我在這裏的挑戰是編寫得到了功能通過文件名,如果它確實存在於表中,則返回值1和其fileID,如果不返回值0和ID 0

現在,我已經開始了,我想把它作爲一個表但是當試圖使用聲明或者函數內部的語句時卡住了

ALTER FUNCTION [dbo].[booker](
    @filenumber nvarchar(50)) 
RETURNS TABLE 
AS 
    RETURN 
     (
     --NB 
     -- note the challenges am facing i thought of passing a value of FileID to @fn then check if its empty or not, that wont work 
     --- Declare @fid int; // is not accepted inside here 
     -- IF EXISTS (SELECT @fid=FILENUMBER FROM [dbo].[File] WHERE FILENUMBER = @filenumber) // the if statement is wrong here too 
     SELECT FileID 
     FROM [dbo].[File] 
     WHERE FileID = @filenumber 
     -- am left with the above statement where i can extract the FileID but don't know how to check if it exists and if so how to 
     -- return it with a value 1 that shows the record is in and value 0, fileid=0 if there is no record 
) 
+0

爲什麼你需要帶表格? – Viki888

回答

0

使用多條件表值函數如下所示,根據您的邏輯使用多個代碼塊。您正在使用內嵌表值函數,它只允許單個SELECT語句。

ALTER FUNCTION [dbo].[booker](@filenumber nvarchar(50)) 
RETURNS @ResultTableVariable TABLE (FileID INT, IsExist INT) 
AS 
    BEGIN 

     IF NOT EXISTS (SELECT 1 FROM [dbo].[File] WHERE FileName= @filenumber) 
     BEGIN 
      INSERT INTO @ResultTableVariable (FileID , IsExist) 
      SELECT 0 , 0 
     END 
     ELSE 
     BEGIN 
     INSERT INTO @ResultTableVariable (FileID , IsExist) 
     SELECT FileID, 1 
     FROM [dbo].[File] 
     WHERE FileID = @filenumber 
     END 

    RETURN 
END 

這將返回一個表有兩列FileIDIsExist

+0

它更高級的IF說法「不正確的語法附近IF 期待'('SELECT或WITH。 」 並且必須聲明一個標量變量@filenumber並且還拒絕了右括號'''' – Bels

+0

您需要的是多語句表價值函數。請檢查鏈接... http://www.sqlservercentral.com/blogs/discussionofsqlserver/2012/02/15/comparing-inline-and-multistatement-table-valued-functions/ –

+0

請檢查編輯答案,並查看鏈接匹配語法 –

0

,但是當我改變mhasan的代碼存儲過程,它的工作

ALTER PROCEDURE [dbo].[booker](
@filenumber nvarchar(50)) 

AS 

    IF NOT EXISTS (SELECT 1 FROM [dbo].[File] WHERE FileNumber= @filenumber) 
    BEGIN 
     SELECT 0 As FileID, 0 As IsExist 
    END 
    ELSE 
    BEGIN 
    SELECT FileID, 1 As IsExist 
    FROM [dbo].[File] 
    WHERE FileNumber = @filenumber 
    END 

我認爲我將使用這一段時間,謝謝你

0

從你的問題,獲取數據爲似乎是無效的方法

您可以按照功能單一值用下面的查詢

CREATE FUNCITON [dbo].[booker](@filenumber nvarchar(50)) RETURNS nvarchar(10) DETERMINISTIC 

BEGIN 
    DECLARE fileDetail nvarchar(10); 
    DECLARE @IDValue INT; 

    SET fileDetail = ''; 
    SET @IDValue = 0; 

    SELECT FileID INTO @IDValue 
    FROM [dbo].[File] 
    WHERE FileID = @filenumber; 

    IF IDValue = 0 THEN 
     SET fileDetail := 0 +'|'+0; 
    ELSE 
     SET fileDetail := 1 +'|'[email protected]; 
    END IF; 

RETURN (fileDetail); 
END 

希望這應該幫助你獲取數據。