转换nvarchar值'SELECT * FROM时转换失败

时间:2011-10-07 05:24:44

标签: sql-server-2008

使用Sql Server 2008,开发了一个视图“vw_MasterView”我收到此错误:

Conversion failed when converting the nvarchar value 'SELECT * FROM VW_MASTERVIEW v WHERE 1=1  AND v.ClinicId = '' to data type int.

当我运行以下存储过程时:

USE [xxxxxxx]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ClientSummary1]
    @LocationId int,
    @startDate datetime,
    @endDate datetime,
    @userName nvarchar(50)
AS
    declare @sql nvarchar(2000);
    SET NOCOUNT ON
    set @sql = 'SELECT * FROM VW_MASTERVIEW v WHERE 1=1 ';
    IF @LocationId is not null
    begin
        set @sql = @sql + ' AND v.LocationId = ''' + @LocationId + '''';
    end
    if @userName is not null
    begin
        set @sql = @sql + ' AND (v.FirstUser = '' OR v.SecondUser = '')' + @userName + '''';
    end
    if @startDate is not null 
    begin
       set @sql = @sql + ' AND v.FirstVisitDate = ''' + @startDate + ''''; 
    end
    if @endDate is not null 
    begin
        set @sql = @sql + ' AND v.LastVisitDate = ''' + @endDate + ''''; 
    end

    EXEC(@sql)

我从VS2010应用程序中获取了LocationId和userName。 在此先感谢

1 个答案:

答案 0 :(得分:4)

在SQL Server中将字符串附加在一起时,必须将非文本类型(例如int)转换为文本类型(例如varchar):

set @sql = @sql + ' AND v.LocationId = ''' +
    cast(@LocationId as varchar(10)) + '''';
--  ^^^^ have to cast           ^^ make sure size is big enough

请注意,首先不需要动态SQL。您可以直接使用参数运行查询(我使用额外的or条件实现了空检查):

SELECT * FROM VW_MASTERVIEW v
 WHERE (v.LocationId = @LocationId    OR @LocationId is null)
   AND (v.FirstUser = @userName OR v.Seconduser = @userName OR @userName is null)
   AND (v.FirstVisitDate = @startDate OR @startDate is null)
   AND (v.LastVisitDate = @endDate    OR @endDate is null)

我可能没有FirstUserSecondUser的逻辑 - 我从你不完整的代码中接受了有根据的猜测。

希望这有帮助!