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.
Related
I understand the error, I am simply not sure why this is occurring. I have written a simple insert procedure to update a list of users.
Error:
Msg 206, Level 16, State 2, Procedure addNewUser, Line 0 [Batch Start Line 2]
Operand type clash: int is incompatible with date
Procedure declaration:
CREATE PROCEDURE [dbo].[addNewUser]
#fName VARCHAR(255),
#lname VARCHAR(255),
#dob DATE,
#email VARCHAR(255),
#gender VARCHAR(255),
#level VARCHAR(255) AS
INSERT INTO [dbo].[User] ([firstname], [lastname], [dob], [email], [gender], [accesslevel])
VALUES ('#fName ', N'#lname', #dob, N'#email', N'#gender', N'#level')
Calling procedure:
DECLARE #return_value int
EXEC #return_value = [dbo].[addNewUser]
#fName = N'Ste',
#lname = N'King',
#dob = 19780103,
#email = N'Books#email.com',
#gender = N'Male',
#level = N'Free'
SELECT 'Return Value' = #return_value
GO
Just put #dob = 19780103 into quotes '1978-01-03':
USE [t7068097]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[addNewUser]
#fName = N'Ste',
#lname = N'King',
#dob = '1978-01-03',
#email = N'Books#email.com',
#gender = N'Male',
#level = N'Free'
SELECT 'Return Value' = #return_value
GO
UPDATE:
SELECT CAST('1978-1-1' AS DATE)
SELECT CAST('19780101' AS DATE)
First your procedure is wrong. You shouldn't put your variables into the single quote for your purpose:
ALTER PROCEDURE [dbo].[addNewUser]
#fName varchar(255),
#lname varchar(255),
#dob DATE,
#email varchar(255),
#gender varchar(255),
#level varchar(255)
AS
INSERT [dbo].[User]
(
[firstname]
, [lastname]
, [dob]
, [email]
, [gender]
, [accesslevel]
)
VALUES
(
#fName
, #lname
, #dob
, #email
, #gender
, #level
)
GO
Also you send int value to the date field. You need yo put into the single quote:
DECLARE #return_value int
EXEC #return_value = [dbo].[addNewUser]
#fName = N'Ste',
#lname = N'King',
#dob = '19780103',
#email = N'Books#email.com',
#gender = N'Male',
#level = N'Free'
SELECT 'Return Value' = #return_value
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.
I would like have a generic procedure to Update my look Up Table.
CREATE TYPE S_Reference.[ReferenceType] as TABLE (
[Id] SMALLINT NOT NULL PRIMARY KEY,
[Code] VARCHAR(16) UNIQUE NOT NULL,
[Rank] SMALLINT NOT NULL CHECK([Rank]>0),
[Description] VARCHAR(128) NOT NULL,
[Base] BIT NOT NULL DEFAULT 0);
GO
CREATE PROCEDURE [S_Reference].[P_B_ReferenceMerge]
#Values [ReferenceType] READONLY,
#TableName NVARCHAR(50)
AS
DECLARE #SQLQuery NVARCHAR(200)
SET #SQLQuery = 'SELECT * FROM ' + #TableName
MERGE INTO #SQLQuery Ori
USING
#Values New
ON (Ori.[Id] = New.[Id])
WHEN MATCHED THEN
UPDATE
SET Ori.[Code] = New.[Code],
Ori.[Rank] = New.[Rank],
Ori.[Description] = New.[Description],
Ori.[Base] = New.[Base]
WHEN NOT MATCHED THEN
INSERT (Ori.[Id] , Ori.[Code], Ori.[Rank],Ori.[Description] ,Ori.[Base])
Values (New.[Id] , New.[Code], New.[Rank],New.[Description] ,New.[Base]);
RETURN 0
But I don't know how to use the "tableName" ?
I get an error on Ori.[Id], I think the problem comes from
SET #SQLQuery = 'SELECT * FROM ' + #TableName
MERGE INTO #SQLQuery Ori
If can help this is how I did. By this way You can manage easily the values in your look up (reference or enum in c#).
First the procedure:
CREATE TYPE S_Reference.[ReferenceType] AS TABLE (
[Id] SMALLINT NOT NULL PRIMARY KEY,
[Code] VARCHAR(40) UNIQUE NOT NULL,
[Rank] SMALLINT UNIQUE NOT NULL CHECK([Rank]>0),
[Description] VARCHAR(128) NOT NULL,
[Base] BIT NOT NULL DEFAULT 0);
GO
CREATE PROCEDURE [S_Reference].[P_M_ReferenceMerge]
#Values S_Reference.[ReferenceType] READONLY,
#TableName NVARCHAR(50)
AS
CREATE TABLE #NewValues (
[Id] SMALLINT NOT NULL PRIMARY KEY,
[Code] VARCHAR(40) UNIQUE NOT NULL,
[Rank] SMALLINT UNIQUE NOT NULL CHECK([Rank]>0),
[Description] VARCHAR(128) NOT NULL,
[Base] BIT NOT NULL DEFAULT 0);
Insert INTO #NewValues
select * From #Values
DECLARE #SQLQuery NVARCHAR(MAX)
SET #SQLQuery =
'DELETE
FROM ' + #TableName + '
WHERE [Id] IN (SELECT [Id]
FROM ' + #TableName + '
EXCEPT
SELECT [Id]
FROM #NewValues)
MERGE INTO ' + #TableName + ' Ori
USING #NewValues New
ON (Ori.[Id] = New.[Id])
WHEN MATCHED THEN
UPDATE
SET Ori.[Code] = New.[Code],
Ori.[Rank] = New.[Rank],
Ori.[Description] = New.[Description],
Ori.[Base] = New.[Base]
WHEN NOT MATCHED THEN
INSERT ([Id] , [Code], [Rank], [Description] ,[Base])
Values (New.[Id] , New.[Code], New.[Rank], New.[Description] ,New.[Base]);'
EXEC sp_executesql #SQLQuery
RETURN 0
Usage
INSERT INTO
#VALUES([Id],[Code],[Rank],[Description] ,[Base])
Values
(1,'EUR',1,'EUR',0),
(2,'GBP',2,'GBP',0),
(3,'USD',3,'USD',0)
EXEC [S_Reference].[P_M_ReferenceMerge]
#Values = #VALUES,
#TableName = 'S_Reference.T_R_Currency'
DELETE FROM #VALUES
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
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) ) + ''' '