Using Sql Server 2008, developed a view “vw_MasterView” I get this error:
Conversion failed when converting the nvarchar value 'SELECT * FROM VW_MASTERVIEW v WHERE 1=1 AND v.ClinicId = '' to data type int.
when I run the following stored procedure:
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)
I get both the LocationId and userName from a VS2010 application.
Thanks in Advance
When appending strings together in SQL Server, you have to cast non-textual types (such as
int) to a textual type (such asvarchar):Note that dynamic SQL should not be necessary in the first place. You can just run the query directly with the parameters (I implemented the null checks with the extra
orconditions):I may not have the logic right for
FirstUserandSecondUser– I took an educated guess from your incomplete code.Hope this helps!