问题
I am trying to create a stored procedure which will check for a list names in a table and there corresponding (boolean/bit) values, even if one of record has value as true, stored procedure should return True, if not then return false.
Here's the table,
Table Name - FruitCrate
Column A (VarChar (Max)) - FruitName
Column B (bit) - Eatable
Now I want a stored procedure whom I can provide a List FruitNames and it checks if any of them is eatable then return true otherwise false.
Not sure how to get started as never sent list as parameter to stored procedure.
Edit
This is what I am trying but getting syntax error,
Create PROCEDURE [dbo].[ProcedureName]
(
@FruitNames varchar(max)
)
AS
Select * From
(SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ '))
WHERE FruitCrate.Eatable= 1
Error **
... Incorrect syntax near ')'.... Incorrect syntax near the keyword 'WHERE'.
**
回答1:
Step 1: You can send your fruitNames as a comma separated (or any other delimiter which is not in any fruit names, ex '!'
or '|'
) string
Step 2: You need a Table Valued T-Sql Function to split a delimited string (Such as this) (say, table column name is myColumn
)
CREATE FUNCTION Split (@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (myColumn nvarchar(500))
AS
BEGIN
--Function body
RETURN @Results
END
Step 3: Write a stored procedure to compare splitted fruitenames with the table.
CREATE PROCEDURE CheckEatables
@fruitName nVarchar(4000) --Change the length as required
AS
BEGIN
SELECT FruitName, COALESCE(Eatable,0) Eatable
FROM FruitCrate fc JOIN dbo.Split(@fruitNames,',') fn
ON fc.FruitName = fn.myColumn
END
回答2:
You can refer to this question, which uses a comma separated list of ID.
You will have same implementation in your stored procedure
来源:https://stackoverflow.com/questions/18695466/stored-procedure-confusion