Stored procedure not getting called in SQL - sql

I have two stored procedures, one calling the other.Though there is no error at compilation in any of them, but on running SearchProcedure, the outputprocedure is not called from with in. I see no reason it not being called. SearchProcedure has been working fine so far.
Please direct what might be the issue.
I know OutputProcedureis not being called as I tried using Select statements in it.
Here is the code:
Calling as follows:
Exec SearchProcedure #firstname ='Simran', #middlename='kaur', #lastname = 'Khurana', #City='Delhi'
Procedures:
CREATE Procedure OutputProcedure
(
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
)
AS
BEGIN
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int
DECLARE #variableTable TABLE (
idx int identity(1,1),
matchvalue nvarchar(15))
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
declare #sql3 nvarchar(300), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter <= #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #sql = 'declare' +' ' + '#Temp'+ #colVar
exec #sql
select #sql as 'SQLFORDECLARATIONS'
set #temp = CHARINDEX(' ',#sql)
select #temp as 'resultofcharindex'
set #temp2 = #temp + 1
SELECT #temp2 AS 'AFTERADDING1'
set #tempresultStore = Right(#sql, #temp2)
SELECT #tempresultStore AS 'FINALCUTPART'
set #sql3 = 'SET ' + #sql2 + '= set ' + ' ' + #tempresultStore + '=' + 'dbo.[Match' + #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar + 'FromTable' + ',' + 0 + ')'
EXEC #sql3
select #sql3 as 'check sql query formed'
set #finalResult = #finalResult + #sql2
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #Percentage = #finalResult/#maxvalue
SELECT #Percentage AS 'FINALRESULT'
RETURN
END
create procedure SearchProcedure
(
#firstname nvarchar(20),
#middlename nvarchar(20) = null,
#lastname nvarchar(20),
#DOB Date = null,
#SSN nvarchar(30)= null,
#ZIP nvarchar(10)= null,
#StateOfResidence nvarchar(2)= null,
#City nvarchar(20)= null,
#StreetName nvarchar(20)= null,
#StreetType nvarchar(20)= null,
#BuildingNumber int= null,
#Aptnumber nvarchar(10)= null
)
As
DECLARE #sSQL NVARCHAR(2000), #Where NVARCHAR(1000) = ' '
declare #Percent int,
#FN nvarchar(20),
#MN nvarchar(20) = null,
#LN nvarchar(20),
#DateOfB Date = null,
#SSNumber nvarchar(30)= null,
#ZIPCode nvarchar(10)= null,
#StateOfRes nvarchar(2)= null,
#CityOfRes nvarchar(20)= null,
#StreetNameRes nvarchar(20)= null,
#StreetTypeRes nvarchar(20)= null,
#BuildingNumberRes int= null,
#AptnumberRes nvarchar(10)= null
set #Percent = 0
create table #results
(
firstname nvarchar(20) not null,
middlename nvarchar(20),
lastname nvarchar(20)not null,
PercentageMatch int not null,
DOB Date,
SSN nvarchar(30),
ZIP nvarchar(10),
[State] nvarchar(2),
City nvarchar(20),
StreetName nvarchar(20),
StreetType nvarchar(20),
BuildingNumber int,
Aptnumber nvarchar(10)
)
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #FN
open c
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
while ##FETCH_STATUS = 0 BEGIN
/*set #Percent = dbo.[MatchLastName](#lastname, #LN, #Percent)
set #Percent = dbo.[MatchMiddleName](#middlename, #MN, #Percent)
set #Percent = dbo.[MatchCity](#City, #CityOfRes, #Percent)*/
Exec [dbo].[OutputProcedure] #lastname, #LN, #middlename, #MN,#City, #CityOfRes, #Percent output
Insert into #results values
(#FN,#MN,#LN,#Percent, #DateOfB,#SSNumber, #ZIPCode,#StateOfRes,#CityOfRes,#StreetNameRes,#StreetTypeRes,#BuildingNumberRes,#AptnumberRes)
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
end
select * from #results order by PercentageMatch desc
IF OBJECT_ID('tempdb..#results') IS NOT NULL DROP TABLE #results
go

In SearchProcedure is there code missing that sets variable fn; you open your cursor with
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #FN
only i don't see where #fn is set; if the cursor has no rows then the second procedure won't get called as the loop won't run.

Related

Need for two level reference in T-SQL

By using the dynamic SQL, I created a variable name like this:
set #tempresultStore = 'Temp'+#colVar
Now, #tempresultstore has the value 'TempMiddleName', then I declared this variable named TempMiddleName and assigned the value in the same line in dynamic sql query and executed.
The code is as follows :(Scroll down to code line with comment to follow where the problem is)
CREATE Procedure OutputProcedure
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
AS
BEGIN
SELECT #MiddleNameFromTable AS'middlename'
select #LastNameFromTable as 'LASTNAMEFROMTABLE'
select #LastNameFromUser as 'LASTNAMEFROMUser'
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int , #finalpercentage int = 0
DECLARE #variableTable TABLE
(
idx int identity(1,1),
matchvalue nvarchar(15)
)
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
set #finalResult = 0;
declare #sql3 nvarchar(300), #sql4 nvarchar(15), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
DECLARE #ParmeterDefinition nvarchar(500);
set #ParmeterDefinition =
N'#LastNameFromUsnvarchar(20),
#LastNameFromTab nvarchar(20),
#MiddleNameFromUs nvarchar(20),
#MiddleNameFromTab nvarchar(20),
#CityFromUs nvarchar(20),
#CityFromTab nvarchar(20),
#Percent int out'
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter < #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #tempresultStore = 'Temp'+#colVar --here
SELECT #tempresultStore AS 'FINALCUTPART'
select 'JUSTBEFORSQL'
set #sql3 = 'declare #Temp' + #colVar + ' int = dbo.[Match' + #colVar + '](' + #colVar + 'FromUser,' + #colVar + 'FromTable, 0)'
select #sql3 as 'check sql query formed'
EXEC sp_executesql #sql3,
#ParmeterDefinition,
#LastNameFromUs = #LastNameFromUser,
#LastNameFromTab = #LastNameFromTable,
#MiddleNameFromUs = #MiddleNameFromUser,
#MiddleNameFromTab = #MiddleNameFromTable,
#CityFromUs = #CityFromUser,
#CityFromTab = #CityFromTable,
#Percent = #Percentage out
select #Percentage AS 'PERCENTRETRIVED'
set #finalResult = #finalResult + #Percentage /*here #Percentage always remains 0. It is the value returned by the UDF called by the dynamic SQL above.The function does return the value but probably I fail to store it correctly.*/
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #finalpercentage = #finalResult/#maxvalue
SELECT #finalpercentage AS 'FINALRESULT'
RETURN
END
Go
How do I access the int value stored in variable called #TempMIddleName
It should work with output keyword. No need for creating table. I don't know but your code is not correct. You have output parameter #Percent and assign value of function to #TempMiddleName, then you should have not a #Percent as Output but #TempMiddleName.
You get dynamic SQL
declare #TempMiddleName int = dbo.[MatchMiddleName](MiddleNameFromUser,MiddleNameFromTable, 0)
I had answered you once, that you miss # before your variables.
Also you have provided variable #Percent(and others as well) for dynamic query, but you don't assign any value to it. Try changing
SET #sql3 = 'declare #Temp' + #colVar + ' int = dbo.[Match' + #colVar + '](' + #colVar + 'FromUser,' + #colVar + 'FromTable, 0)'
to
SET #sql3 = 'select #Percent = 1'
and you will see that 1 is returned as supposed to.
Also you have error here. Split first parameter from its type
set #ParmeterDefinition =
N'#LastNameFromUsnvarchar(20),
set #ParmeterDefinition =
N'#LastNameFromUs nvarchar(20),
You would need to dynamically create a temporary table, and access it's value by selecting the top 1 value from it. Something like the following;
CREATE TABLE #ResultValue (Value Varchar(200))
DECLARE #DynamicSql NVarchar(MAX) = ''
SELECT #DynamicSql = '
DECLARE #tempresultStore Varchar(50)
DECLARE #colVar Varchar(50) = ''MiddleName''
SET #tempresultStore = ''Temp'' + #colVar
insert into #ResultValue
select #tempresultStore
'
EXEC sp_sqlexec #DynamicSql
SELECT * FROM #ResultValue
DROP TABLE #ResultValue
If you paste all your code we might try to amend it for you.

PRINT not print the dynamic sql

declare #sImport_Table1 table
(
Id int identity(1,1) ,
Zone nvarchar(50),
Sub_Code nvarchar(50),
Geography nvarchar(50),
DayOfWeek nvarchar(50)
)
INSERT INTO #sImport_Table1 SELECT 'A','Z','Geo','SUN'
declare #sZone nvarchar(50)
declare #sSubCode nvarchar(50)
declare #c_Geography nvarchar(50)='Geo'
declare #c_DayOfWeek nvarchar(50)='SUN'
declare #sImport_Table nvarchar(500)='#sImport_Table1'
--SELECT * FROM #sImport_Table1
declare #sQuery nvarchar(4000)
SET #sQuery='SELECT '+ #sZone + ' = Zone,'+
#sSubCode +' = Sub_Code
FROM'+ #sImport_Table +
' WHERE Geography ='+ #c_Geography +
' AND DayOfWeek = '+ #c_DayOfWeek
PRINT #sQuery
*************** EDITED********************************
declare #sImport_Table1 table
(
Id int identity(1,1) ,
Zone nvarchar(50),
Sub_Code nvarchar(50),
Geography nvarchar(50),
DayOfWeek nvarchar(50)
)
INSERT INTO #sImport_Table1 SELECT 'A','Z','Geo','SUN'
declare #sZone nvarchar(50)
declare #sSubCode nvarchar(50)
declare #c_Geography nvarchar(50)='Geo'
declare #c_DayOfWeek nvarchar(50)='SUN'
declare #sImport_Table nvarchar(500)='#sImport_Table1'
--SELECT * FROM #sImport_Table1
declare #sQuery nvarchar(4000)
SET #sQuery='''SELECT #sZone = Zone, '+
'#sSubCode = Sub_Code
FROM '+ #sImport_Table +
' WHERE Geography ='''+ #c_Geography + '''
AND [DayOfWeek] = '''+ #c_DayOfWeek +''''''
PRINT #sQuery
sp_executesql #sQuery
PRINT #sZone
PRINT #sSubCode
You have #sZone and #sSubCode which are null. Concatenation with null is always null.
This can make sense.
SET #sQuery='SELECT #sZone = Zone, '+
'#sSubCode = Sub_Code
FROM '+ #sImport_Table +
' WHERE Geography ='+ #c_Geography +
' AND [DayOfWeek] = '+ #c_DayOfWeek
Notice, that the DayOfWeek is reserved word and must be included in square bracket.

Search with multiple parameters

I want to search infomation about order details.
where #SDateMin as ShipDateMin and #SDateMax as ShipDateMax,
etc..
but when I execute my stored procedure, I get error :
Msg 137, Level 15, State 2, Line 8
Must declare the scalar variable "#spmin"
My T-SQL code is:
ALTER PROC sp_SearchOrderDetails
#FName NVARCHAR(30) = NULL,
#LName NVARCHAR(30)= NULL,
#Status BIT = NULL ,
#SDateMin nvarchar(50) = NULL,
#SDateMax nvarchar(50) = NULL,
#ODateMin nvarchar(50) = NULL,
#ODateMax nvarchar(50) = NULL
AS
BEGIN
DECLARE #SqlStr NVARCHAR(MAX),
#ParamList NVARCHAR(2000)
SELECT #SqlStr = 'SELECT O.* FROM dbo.OrderDetails O where (1=1)'
IF #FName IS NOT NULL
SELECT #SqlStr = #SqlStr + 'AND ( O.FirstName like''%' + #FName + '%'')'
IF #LName IS NOT NULL
SELECT #SqlStr = #SqlStr + 'AND ( O.LastName like''%' + #LName + '%'')'
If #SDateMin IS NOT NULL AND #SDateMax IS NOT NULL
DECLARE #spmin DATE = Convert(DATE,#SDateMin,105)
DECLARE #spmax DATE = Convert(DATE,#SDateMax,105)
SELECT #SqlStr = #SqlStr + 'AND ( O.ShipDate BETWEEN #spmin AND #spmax )'
If #ODateMin IS NOT NULL AND #ODateMax IS NOT NULL
DECLARE #odmin DATE = Convert(DATE,#ODateMin,105)
DECLARE #odmax DATE = Convert(DATE,#ODateMax,105)
SELECT #SqlStr = #SqlStr + 'AND ( O.OrderDate BETWEEN #odmin AND #odmax )'
If #Status IS NOT NULL
SELECT #SqlStr = #SqlStr + 'AND ( O.ShipStatus = #Status )'
SELECT #ParamList = '
#FName nvarchar(30),
#LName nvarchar(30),
#Status bit,
#SDateMin nvarchar(50),
#SDateMax nvarchar(50),
#ODateMin nvarchar(50),
#ODateMax nvarchar(50)'
EXEC SP_EXECUTESQL #SqlStr,
#ParamList,
#FName,
#LName ,
#Status,
#SDateMin,
#SDateMax,
#ODateMin,
#ODateMax
END
exec :
DECLARE #return_value int
EXEC #return_value = [dbo].[sp_SearchOrderDetails]
#SDateMin = N'10-10-2011',
#SDateMax = N'10-10-2012'
SELECT 'Return Value' = #return_value
GO
CREATE TABLE [dbo].[OrderDetails](
[OrderDetailId] [int] IDENTITY(1,1) NOT NULL,
[CustomerTitle] [nvarchar](5) NOT NULL,
[FirstName] [nvarchar](18) NOT NULL,
[LastName] [nvarchar](22) NOT NULL,
[PhoneNumber] [nvarchar](15) NOT NULL,
[Email] [nvarchar](30) NOT NULL,
[Address] [nvarchar](60) NOT NULL,
[Country] [nvarchar](20) NOT NULL,
[ShipStatus] [bit] NOT NULL,
[OrderDate] [datetime] NOT NULL,
[ShipDate] [datetime] NOT NULL,
[PaymentProvider] [nvarchar](20) NOT NULL,
[Deliver] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED
(
[OrderDetailId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
#ParamList contains parameters as they were named in procedure declaration, but later you introduce another similarly named variables. I've also changed datatypes, because converts suggest that they are actually dates.
SELECT #ParamList = '
#FName nvarchar(30),
#LName nvarchar(30),
#Status bit,
#spmin date,
#spmax date,
#odmin date,
#odmax date'
EDIT: I don't understand you last comment. To solve your problem you need to enclose code after IF in a begin ... end block.
ALTER PROC sp_SearchOrderDetails
#FName NVARCHAR(30) = NULL,
#LName NVARCHAR(30)= NULL,
#Status BIT = NULL ,
#SDateMin nvarchar(50) = NULL,
#SDateMax nvarchar(50) = NULL,
#ODateMin nvarchar(50) = NULL,
#ODateMax nvarchar(50) = NULL
AS
BEGIN
DECLARE #SqlStr NVARCHAR(MAX),
#ParamList NVARCHAR(2000)
SELECT #SqlStr = 'SELECT O.* FROM dbo.OrderDetails O where (1=1)'
IF #FName IS NOT NULL
SELECT #SqlStr = #SqlStr + 'AND ( O.FirstName like''%' + #FName + '%'')'
IF #LName IS NOT NULL
SELECT #SqlStr = #SqlStr + 'AND ( O.LastName like''%' + #LName + '%'')'
If #SDateMin IS NOT NULL AND #SDateMax IS NOT NULL
BEGIN
DECLARE #spmin DATE = Convert(DATE,#SDateMin,105)
DECLARE #spmax DATE = Convert(DATE,#SDateMax,105)
SELECT #SqlStr = #SqlStr + 'AND ( O.ShipDate BETWEEN #spmin AND #spmax )'
END
If #ODateMin IS NOT NULL AND #ODateMax IS NOT NULL
BEGIN
DECLARE #odmin DATE = Convert(DATE,#ODateMin,105)
DECLARE #odmax DATE = Convert(DATE,#ODateMax,105)
SELECT #SqlStr = #SqlStr + 'AND ( O.OrderDate BETWEEN #odmin AND #odmax )'
END
If #Status IS NOT NULL
SELECT #SqlStr = #SqlStr + 'AND ( O.ShipStatus = #Status )'
SELECT #ParamList = '
#FName nvarchar(30),
#LName nvarchar(30),
#Status bit,
#spmin date,
#spmax date,
#odmin date,
#odmax date'
EXEC SP_EXECUTESQL #SqlStr,
#ParamList,
#FName,
#LName ,
#Status,
#spmin,
#spmax,
#odmin,
#odmax
END
I would suggest that you do it even when if is followed by one line only, because you never know when you will have to expand that and it is way too easy to forget to put begin and end around new code at that time, because you are solving something else, not proofreading.

SQL stored procedure thowing error when converting parameter, no error with literal

Hi I have problem that I can't solve alone since damn debugging doesn't work on my host.In short When I try to convert type datetime to varchar from one column in Table 1 and using it as parametar to my stored procedure I get error, but when I write exectly same thing but with N'..string...' everything is fine, Im really confused, here it is:
Table 1:
Id(Identifier int, not null)
Message (nvarchar(max)
DisableComments(int)
DateTime(datetime)
Color(nvarchar)
Username(nvarchar)
ID | Message | DisableComments | DateTime | Color | Username
18 | Comment | 0 | 2011-12-18 14:16:27.000 | #000000 | User
Here is query that works fine:
DECLARE #return_value int
SELECT TOP 1 [ID]
,[Message]
,[DisableComments]
,[DateTime]
,[Color]
,[Username]
FROM Thoughts
EXEC #return_value = InsertThoughtToPartition
#ThoughtMessage = Message,
#ThoughtDateTime = N'2012-01-03 01:22:31.000',
#ThoughtColor = Color,
#ThoughtUsername = Username
SELECT 'Return Value' = #return_value
Here is query that throws error: "Conversion failed when converting date and/or time from character string.":
DECLARE #return_value int
SELECT TOP 1 [ID]
,[Message]
,[DisableComments]
,[DateTime]
,[Color]
,[Username]
,CONVERT(nvarchar(MAX),DateTime, 121) as Datei
FROM Thoughts
EXEC #return_value = InsertThoughtToPartition
#ThoughtMessage = Message,
#ThoughtDateTime = Datei,
#ThoughtColor = Color,
#ThoughtUsername = Username
SELECT 'Return Value' = #return_value
And here is my stored procedure that I am executing:
USE [TagCloudDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE InsertThoughtToPartition
(
#ThoughtMessage as nvarchar(MAX),
#ThoughtDateTime as nvarchar(MAX),
#ThoughtColor as nvarchar(MAX),
#ThoughtUsername as nvarchar(MAX)
)
AS
DECLARE #MonthName nvarchar(MAX);
DECLARE #CurrentYear nvarchar(MAX);
DECLARE #InsertTableName nvarchar(MAX);
Declare #CreateTable nvarchar(MAX);
Declare #JustInsert nvarchar(MAX);
SET #CurrentYear = CAST((SELECT DATENAME(year, CAST(#ThoughtDateTime as datetime))) as nvarchar(MAX));
SET #MonthName = CAST((SELECT DATENAME(month, CAST(#ThoughtDateTime as datetime))) as nvarchar(MAX));
SET #InsertTableName = 'Thoughts_' + #MonthName + '_' + #CurrentYear;
IF OBJECT_ID(#InsertTableName) IS NOT NULL
BEGIN
SET #JustInsert = 'INSERT INTO '+ #InsertTableName + '(Message,DateTime,Color,Username)
VALUES('''+ #ThoughtMessage+''',CONVERT(DATETIME,'''+ #ThoughtDateTime +''', 121),'''+#ThoughtColor+''','''+#ThoughtUsername+''')';
EXEC(#JustInsert);
END
ELSE
BEGIN
SET #CreateTable = '
USE [TagCloudDb]
CREATE TABLE ['+ #InsertTableName+'](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[DateTime] [datetime] NOT NULL,
[Color] [nvarchar](max) NOT NULL,
[Username] [nvarchar](max) NOT NULL,
UniqueID as CAST(ID as nvarchar) +''-''+ CONVERT(VARCHAR(8), DateTime, 112)
) ON [PRIMARY]
INSERT INTO '+ #InsertTableName + '(Message,DateTime,Color,Username)
VALUES('''+ #ThoughtMessage+''',CONVERT(DATETIME,'''+ #ThoughtDateTime + ''', 121),'''+#ThoughtColor+''','''+#ThoughtUsername+''')';
EXEC(#CreateTable);
END
GO
here is updated version with DateTime as input and but still I get same error with two queryes: First query works fine agian but when i try to pass Datei or [DateTime] from first table I get Error converting data type nvarchar to datetime.
USE [TagCloudDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE InsertThoughtToPartition
(
#ThoughtMessage as nvarchar(MAX),
#ThoughtDateTime as DateTime,
#ThoughtColor as nvarchar(MAX),
#ThoughtUsername as nvarchar(MAX)
)
AS
DECLARE #MonthName nvarchar(MAX);
DECLARE #CurrentYear nvarchar(MAX);
DECLARE #InsertTableName nvarchar(MAX);
Declare #CreateTable nvarchar(MAX);
Declare #JustInsert nvarchar(MAX);
DECLARE #JustInsertParamDef nvarchar(MAX);
SET #CurrentYear = DATENAME(year, #ThoughtDateTime);
SET #MonthName = DATENAME(month, #ThoughtDateTime);
SET #InsertTableName = 'Thoughts_' + #MonthName + '_' + #CurrentYear;
SET #JustInsert = N'INSERT INTO '+ #InsertTableName + '(Message, DateTime, Color, Username)
VALUES(#ThoughtMessage, #ThoughtDateTime ,#ThoughtColor, #ThoughtUsername)';
SET #JustInsertParamDef = N'#InsertTableName nvarchar(MAX), #ThoughtMessage nvarchar(MAX), #ThoughtDateTime datetime,
#ThoughtColor nvarchar(MAX), #ThoughtUsername nvarchar(MAX)';
IF OBJECT_ID(#InsertTableName) IS NOT NULL
BEGIN
EXECUTE sp_executesql
#JustInsert,
#JustInsertParamDef,
#InsertTableName,
#ThoughtMessage,
#ThoughtDateTime,
#ThoughtColor,
#ThoughtUsername;
END
ELSE
BEGIN
SET #CreateTable = 'USE [TagCloudDb]
CREATE TABLE ['+#InsertTableName+'](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[DateTime] [datetime] NOT NULL,
[Color] [nvarchar](max) NOT NULL,
[Username] [nvarchar](max) NOT NULL,
[UniqueID] as CAST(ID as nvarchar) + ''-'' + CONVERT(VARCHAR(8), DateTime, 112)
) ON [PRIMARY]'
EXEC(#CreateTable);
EXECUTE sp_executesql
#JustInsert,
#JustInsertParamDef,
#InsertTableName = #InsertTableName,
#ThoughtMessage = #ThoughtMessage,
#ThoughtDateTime = #ThoughtDateTime,
#ThoughtColor = #ThoughtColor,
#ThoughtUsername = #ThoughtUsername;
END
The procedure is fine, the execution is not working
Check the contents of your table after you run the working example.
ID|Message|DateTime|Color|Username|UniqueID
1|Message|2012-01-03 01:22:31.000|Color|Username|1-20120103
You aren't passing the values you selected to the procedure, so it's failing when trying to parse 'Dateti' to a DATETIME type
You should definitely clean up your data types and string sizes, that should make things like this easier to catch

Need help build a dynamic query with Between dates in sql server 2008

I have UI where a user can search on optional parameters.I am writing a SP and as a testing database I am using AdventureWorks.
For some reasons I dont seem to find a way how to include
Where ModifiedDate between ''' + #Fromdate + ''' And '''+ #ToDate + '''')
in my existing SP.Can you help?
My sp looks like this
ALTER PROCEDURE SearchPerson_Dynamic
(
#FirstName NVARCHAR(50) = NULL,
#LastName NVARCHAR(50) = NULL,
#EmailAddress NVARCHAR(50) = NULL,
#Phone NVARCHAR(25) = NULL,
#FromDate DATETIME =NULL,
#ToDate DATETIME =NULL
AS
DECLARE #sSQL NVARCHAR(MAX), #Where NVARCHAR(1000) = ''
SET #sSQL = 'SELECT * FROM [Person].[Contact]'
IF #FirstName is not null
SET #Where = #Where + 'AND FirstName = #_FirstName '
IF #LastName is not null
SET #Where = #Where + 'AND LastName = #_LastName '
IF #EmailAddress IS NOT NULL
SET #Where = #Where + 'AND EmailAddress = #_EmailAddress '
IF #Phone IS NOT NULL
SET #Where = #Where + 'AND Phone = #_Phone '
-- NEED TO INTEGRATE A SEARCH BETWEEN #FromDate and #ToDate
IF LEN(#Where) > 0
SET #sSQL = #sSQL + 'WHERE ' + RIGHT(#Where, LEN(#Where)-3)
EXEC sp_executesql #sSQL,
N'#_FirstName VARCHAR(50),
#_LastName VARCHAR(50),
#_EmailAddress VARCHAR(50),
#_Phone NVARCHAR(25)',
#_FirstName = #FirstName,
#_LastName = #LastName,
#_EmailAddress = EmailAddress,
#_Phone = #Phone
MISSING #FROMDate and #ToDate --HOW DO i DO IT HERE
One thing I have not done is that some fields EG Surname the user can select "ALL" in the UI from the drop down. How would I implement a search where I dont have an exact parameter?
Thanks again for your help
If I was to rewrite your stored proc, I would do the following
ALTER PROCEDURE SearchPerson_Dynamic
(
#FirstName NVARCHAR(50) = NULL,
#LastName NVARCHAR(50) = NULL,
#EmailAddress NVARCHAR(50) = NULL,
#Phone NVARCHAR(25) = NULL,
#FromDate DATETIME =NULL,
#ToDate DATETIME =NULL
)
as
begin
SELECT * FROM [Person].[Contact]
where
FirstName = coalesce(#FirstName, FirstName) and
LastName = coalesce(#LastName, LastName) and
EmailAddress = coalesce(#EmailAddress, EmailAddress) and
Phone = coalesce(#Phone, Phone) and
ModifiedDate >= coalesce(#FromDate, FromDate) and
ModifiedDate <= coalesce(#ToDate, ToDate)
end
This is better as its not executing text for the stored procedure and could be optimized.
If you want to use the dynamic sql, you could cast the date to a normal string, ie
IF #FromDate IS NOT NULL AND #ToDate IS NOT NULL
SET #Where = #Where + 'AND ModifiedDate between ''' + cast( #FromDate as varchar(50) ) + ''' and ''' + cast( #ToDate as varchar(50) ) + ''' '