DECLARE @CityId AS VARCHAR(20) = NULL
DECLARE @CityList AS VARCHAR(20) = '1, 2, 3, 4, 5';
IF (@CityId IS NULL)
SET @CityId = @CityList;
SELECT *
FROM City
WHERE CityID IN (@CityId)
我有一个列出所有城市的存储过程。但是如果设置了参数,那么它应该只显示有关该城市的特定信息。 City Table中的CityID是bigint。如果CityId保留为null,则会显示错误消息“ 将数据类型varchar转换为bigint时出错。 '
注意:如果我构造以下查询,一切似乎都没问题。
SELECT * FROM City WHERE CityID IN (1, 2, 3, 4, 5)
但如果我继续使用以下查询,则会出错。
SELECT * FROM City WHERE CityID IN ('1, 2, 3, 4, 5')
我想我应该在这种情况下构建int数组,但我不知道该怎么做。 有什么建议吗?
答案 0 :(得分:3)
您可以使用动态SQL
exec('SELECT * FROM City WHERE CityID IN (' + @CityId + ')')
答案 1 :(得分:1)
试试这个:
IF (@CityId IS NULL)
SET @CityId = ',' + REPLACE(@CityList, ' ', '') + ',';
ELSE
SET @CityId = ',' + @CityId + ',';
SELECT *
FROM City
WHERE charindex(',' + CAST(CityID as nvarchar(20)) + ',', @CityId) > 0
答案 2 :(得分:1)
DECLARE @CityId AS VARCHAR(20) = NULL
DECLARE @CityList AS VARCHAR(20) = '1, 2, 3, 4, 5';
IF (@CityId IS NULL)
SET @CityId = @CityList;
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = N'
SELECT *
FROM City
where
1 = 1
AND Cityid in ('+@CityId+')
';
SELECT @SQL = @SQL + N' ';
EXEC Sp_executeSQL
@SQL
答案 3 :(得分:0)
存储过程
DELIMITER $$
DROP PROCEDURE IF EXISTS `mystoredprocedure`$$
CREATE PROCEDURE `mystoredprocedure`(IN city_id AS VARCHAR(20))
BEGIN
SET @CityId = city_id;
SET @where_condition = "";
IF (@CityId IS NULL) THEN
SET @where_condition = CONCAT(@where_condition,"1, 2, 3, 4, 5");
ELSE
SET @where_condition = @CityId;
END IF;
SET @query = CONCAT("SELECT * FROM City WHERE CityID IN (",@where_condition,")");
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
致电声明
CALL `mystoredprocedure`(NULL);
OR
CALL `mystoredprocedure`('1,2,3');