What is the result of print @STR ?
I think it will be empty as you are building @strqry up with a potential outcome that it will be null. When you add the to @STR you will end up with a null string and therefore no query to run.
The following is one way round the problem
@transfrmdt date,
@transtodt date,
@cid integer,
@Type char(1)
DEClare @strqry varchar(max)
DEClare @STR varchar(max)
set @strqry= 'select name from Mas_C where 1 = 1 '
If (@Type<>'')
BEGIN
SET@strqry= @strqry +' and type='''+@Type+''''
END
If (@cname<>'')
BEGIN
SET@strqry= @strqry +' and cid='''+@cid+''''
END
SET @STR =' SELECT convert(varchar (10),transdt,111)as Transdt,amt
FROM Transcation WHERE 1=1
and Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111) '
+@strqry
print @STR
exec(@str)
SELECT sum(Amt) as TotalAmt
FROM Transcation WHERE Transdt between convert(varchar (10),@transfrmdt,111) and convert(varchar (10),@transtodt,111)
(Edited to add)
I ran the query above (with @type and @cname as empty) and got the following:-
SELECT CONVERT(VARCHAR(10), transdt, 111) AS Transdt ,
amt
FROM Transcation
WHERE 1 = 1
AND Transdt BETWEEN CONVERT(VARCHAR(10), @transfrmdt, 111)
AND CONVERT(VARCHAR(10), @transtodt, 111)
SELECT name
FROM Mas_C
WHERE 1 = 1
I'm not sure if you wanted two separate queries, or if you wanted to have the second as a filter for name.
-------------------------------Posting Data Etiquette - Jeff Moden [/url]Smart way to ask a question
There are naive questions, tedious questions, ill-phrased questions, questions put after inadequate self-criticism. But every question is a cry to understand (the world). There is no such thing as a dumb question. ― Carl Sagan
I would never join a club that would allow me as a member - Groucho Marx