mssql dynamic query entity does not get values - sql-server

hello this my dynamic query and this procedure I did tested is working.
but Does not bring data to the server-side (entity)
visual studio 2012
framework 4.5
entity store procedure
public IEnumerable<spGetInvoiceDetailSearch_Result> GetInvoiceDetailedSearch(InvoiceModel item)
{
return DALContext.GetInvoiceDetailedSearch(item);
}
ALTER PROCEDURE [dbo].[spGetInvoiceDetailSearch] #InvoiceItemID INT
,#InvoiceTypeID INT
,#VesselID INT
,#PaidBy NVARCHAR(50)
,#InvoiceNo NVARCHAR(50)
,#CompanyID INT
,#InvoiceFromDate DATE
,#InvoiceToDate DATE
,#FromDueDate DATE
,#ToDueDate DATE
,#FromAmount DECIMAL(18, 4)
,#ToAmount DECIMAL(18, 4)
,#DueDateType NVARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(4000)
SELECT #SQLQuery =
'SELECT dbo.Invoices.InvoiceID, dbo.Invoices.CompanyID, dbo.Invoices.VesselID, dbo.Invoices.InvoiceNo, dbo.Invoices.DueDate, dbo.Invoices.Amount,
dbo.Invoices.Comment, dbo.Invoices.IsPaid, dbo.Invoices.PaymentDate, dbo.Invoices.PaidBy, dbo.Invoices.Period, dbo.Invoices.InvoiceDate,
dbo.Invoices.InvoiceCurrencyCode, dbo.Invoices.InvoiceAmount, dbo.Invoices.IsReceived, dbo.Invoices.IsProforma, dbo.Invoices.InvoiceTypeID,
dbo.Invoices.IsDeleted, dbo.Invoices.Parity, dbo.Invoices.DueDateType, dbo.Vessels.Name AS VesselName, dbo.InvoiceVsInvoiceItems.ItemPrice as ItemPrice,
dbo.InvoiceVsInvoiceItems.InvoiceItemID as InvoiceItemID, dbo.InvoiceVsInvoiceItems.VAT as VAT, dbo.InvoiceVsInvoiceItems.ItemType as ItemType, dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName
FROM dbo.Invoices LEFT OUTER JOIN
dbo.Companies ON dbo.Invoices.CompanyID = dbo.Companies.CompanyID LEFT OUTER JOIN
dbo.InvoiceTypes ON dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID LEFT OUTER JOIN
dbo.InvoiceVsInvoiceItems ON dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID LEFT OUTER JOIN
dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceVsInvoiceItemID = dbo.InvoiceItems.InvoiceItemID LEFT OUTER JOIN
dbo.Vessels ON dbo.Invoices.VesselID = dbo.Vessels.VesselID WHERE
dbo.Invoices.IsDeleted != 1
and dbo.Vessels.IsDeleted != 1
and dbo.Companies.IsDeleted != 1 '
SET FMTONLY OFF
IF #InvoiceItemID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.InvoiceItems.InvoiceItemID= ''' + CAST(#InvoiceItemID AS NVARCHAR(50)) + ''''
END
IF #InvoiceTypeID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceTypeID= ''' + CAST(#InvoiceTypeID AS NVARCHAR(50)) + ''''
END
IF #VesselID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID= ''' + CAST(#VesselID AS NVARCHAR(50)) + ''''
END
IF #PaidBy IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.PaidBy = ''' + CAST(#PaidBy AS NVARCHAR(50)) + ''''
END
IF #InvoiceNo IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.InvoiceNo = ''' + CAST(#InvoiceNo AS NVARCHAR(50)) + ''''
END
IF #CompanyID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = ''' + CAST(#CompanyID AS NVARCHAR(50)) + ''''
END
IF #FromAmount IS NOT NULL AND #ToAmount IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.Amount BETWEEN ''' + CAST(#FromAmount AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToAmount AS NVARCHAR(100)) + ''''
END
IF #DueDateType IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.DueDateType = ''' + CAST(#DueDateType AS NVARCHAR(50)) + ''''
END
IF #InvoiceFromDate IS NOT NULL AND #InvoiceToDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceDate Between ''' + CAST(#InvoiceFromDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#InvoiceToDate AS NVARCHAR(100)) + ''''
END
IF #FromDueDate IS NOT NULL AND #ToDueDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDate Between ''' + CAST(#FromDueDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToDueDate AS NVARCHAR(100)) + ''''
END
EXECUTE (#SQLQuery)
END
and end question
my table date type : date format but
server shows it like datetime how can I do to change it to date format..
thank you
regards

ALTER PROCEDURE [dbo].[spGetInvoiceDetailSearch] #InvoiceItemID INT
,#InvoiceTypeID INT
,#VesselID INT
,#PaidBy NVARCHAR(50)
,#InvoiceNo NVARCHAR(50)
,#CompanyID INT
,#InvoiceFromDate DATE
,#InvoiceToDate DATE
,#FromDueDate DATE
,#ToDueDate DATE
,#FromAmount DECIMAL(18, 4)
,#ToAmount DECIMAL(18, 4)
,#DueDateType NVARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(4000)
SELECT #SQLQuery =
'SELECT dbo.Invoices.InvoiceID, dbo.Invoices.CompanyID, dbo.Invoices.VesselID, dbo.Invoices.InvoiceNo, dbo.Invoices.DueDate, dbo.Invoices.Amount,
dbo.Invoices.Comment, dbo.Invoices.IsPaid, dbo.Invoices.PaymentDate, dbo.Invoices.PaidBy, dbo.Invoices.Period, dbo.Invoices.InvoiceDate,
dbo.Invoices.InvoiceCurrencyCode, dbo.Invoices.InvoiceAmount, dbo.Invoices.IsReceived, dbo.Invoices.IsProforma, dbo.Invoices.InvoiceTypeID,
dbo.Invoices.IsDeleted, dbo.Invoices.Parity, dbo.Invoices.DueDateType, dbo.Vessels.Name AS VesselName, dbo.InvoiceVsInvoiceItems.ItemPrice as ItemPrice,
dbo.InvoiceVsInvoiceItems.InvoiceItemID as InvoiceItemID, dbo.InvoiceVsInvoiceItems.VAT as VAT, dbo.InvoiceVsInvoiceItems.ItemType as ItemType, dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName
FROM dbo.Invoices LEFT OUTER JOIN
dbo.Companies ON dbo.Invoices.CompanyID = dbo.Companies.CompanyID LEFT OUTER JOIN
dbo.InvoiceTypes ON dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID LEFT OUTER JOIN
dbo.InvoiceVsInvoiceItems ON dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID LEFT OUTER JOIN
dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceVsInvoiceItemID = dbo.InvoiceItems.InvoiceItemID LEFT OUTER JOIN
dbo.Vessels ON dbo.Invoices.VesselID = dbo.Vessels.VesselID WHERE
dbo.Invoices.IsDeleted != 1
and dbo.Vessels.IsDeleted != 1
and dbo.Companies.IsDeleted != 1 '
SET FMTONLY OFF
IF #InvoiceItemID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.InvoiceItems.InvoiceItemID= ' + CAST(#InvoiceItemID AS NVARCHAR(50)) + ''
END
IF #InvoiceTypeID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceTypeID= ' + CAST(#InvoiceTypeID AS NVARCHAR(50)) + ''
END
IF #VesselID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID= ' + CAST(#VesselID AS NVARCHAR(50)) + ''
END
IF #PaidBy IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.PaidBy = ''' + CAST(#PaidBy AS NVARCHAR(50)) + ''''
END
IF #InvoiceNo IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceNo = ''' + CAST(#InvoiceNo AS NVARCHAR(50)) + ''''
END
IF #CompanyID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = ' + CAST(#CompanyID AS NVARCHAR(50)) + ''
END
IF #FromAmount IS NOT NULL AND #ToAmount IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.Amount BETWEEN ''' + CAST(#FromAmount AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToAmount AS NVARCHAR(100)) + ''''
END
IF #DueDateType IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDateType = ''' + CAST(#DueDateType AS NVARCHAR(50)) + ''''
END
IF #InvoiceFromDate IS NOT NULL AND #InvoiceToDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceDate Between ''' + CAST(#InvoiceFromDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#InvoiceToDate AS NVARCHAR(100)) + ''''
END
IF #FromDueDate IS NOT NULL AND #ToDueDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDate Between ''' + CAST(#FromDueDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToDueDate AS NVARCHAR(100)) + ''''
END
PRINT (#SQLQuery)
END
First of all, debugging it's very easy. Replace EXEC(#SQLQUery) with print and then you see your actual query.
You had some sintax error ( some places where AND was missing a space in front) and also you have some interger that were treated as strings.
Try my updated procedure.

It seems that procedure is getting called properly but no rows are getting returned, to debug the exact problem you can write actual hardcoded query returning 1 or more records instead of dynamic query.
So after doing that there are two possibilities
procedure call via edmx returns data, that means parameter values are causing some problem.
Any Data is not returned.
To solve any of the problem you need to check corresponding sql query which is getting generated while calling SP via Enitity Framework.

Related

Microsoft SQL Server : find & UPDATE exact value in hall database even if it's PRIMARY

I want to change a specific value at unknown table or column. I reached to the code helped me to search it. I found that at some tables, it's the primary column.
I must do this job because I have a lot of values that need to be changed.
I tried to do the code but I got lot of errors:
Invalid column name 'TableNameA'.
Invalid column name 'ColumnNameA'.
Hope get help as I'm still new for SQL.
What should I do?
DECLARE #SearchStrTableName nvarchar(255), #SearchStrColumnName nvarchar(255), #SearchStrColumnValue nvarchar(255), #SearchStrInXML bit, #FullRowResult bit, #FullRowResultRows int
SET #SearchStrColumnValue = '4523'
Declare #NewValueInt int = 4195403
Declare #NewValueVarChar nvarchar(20) = '4194523'
/* use LIKE syntax */
SET #FullRowResult = 1
SET #FullRowResultRows = 3
SET #SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET #SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET #SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE #TableName nvarchar(256) = '',#ColumnName nvarchar(128),#ColumnType nvarchar(20), #QuotedSearchStrColumnValue nvarchar(110), #QuotedSearchStrColumnName nvarchar(110)
SET #QuotedSearchStrColumnValue = QUOTENAME(#SearchStrColumnValue,'''')
DECLARE #ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE #TableName IS NOT NULL
BEGIN
SET #TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(#SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > #TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF #TableName IS NOT NULL
BEGIN
DECLARE #sql VARCHAR(MAX)
SET #sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + #TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + #TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(#SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE #SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN #SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + #SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO #ColumnNameTable
EXEC (#sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM #ColumnNameTable)
BEGIN
PRINT #ColumnName
SELECT TOP 1 #ColumnName = COLUMN_NAME,#ColumnType = DATA_TYPE FROM #ColumnNameTable
SET #sql = 'SELECT ''' + #TableName + ''',''' + #ColumnName + ''',' + CASE #ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + #ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + '),'''
ELSE 'LEFT(' + #ColumnName + ', 4096),''' END + #ColumnType + '''
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + CASE #ColumnType WHEN 'xml' THEN 'CAST(' + #ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + ')'
ELSE #ColumnName END + ' LIKE ' + #QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(#sql)
IF ##ROWCOUNT > 0 IF #FullRowResult = 1
BEGIN
SET #sql = 'SELECT TOP ' + CAST(#FullRowResultRows AS VARCHAR(3)) + ' ''' + #TableName + ''' AS [TableFound],''' + #ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + CASE #ColumnType WHEN 'xml' THEN 'CAST(' + #ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + ')'
ELSE #ColumnName END + ' LIKE ' + #QuotedSearchStrColumnValue
EXEC(#sql)
DECLARE #sqlU VARCHAR(MAX)
Declare #sqlN VARCHAR(MAX)
SET #sqlU = N'UPDATE ' + quotename(#SearchStrTableName) + ' SET ' +quotename(#SearchStrColumnName)+ ' = ''' +#NewValueVarChar+ ''' WHERE ' +quotename(#SearchStrColumnName)+ ' = ''' + #SearchStrColumnValue + '''';
EXEC (#sqlU)
SET #sqlN = N'Update ' + quotename(#SearchStrTableName) + ' SET '+ quotename(#SearchStrColumnName) +'=''' +#NewValueVarChar+ '''where'+ quotename(#SearchStrColumnName) + '='+ #SearchStrColumnValue
EXEC (#sqlN)
END
DELETE FROM #ColumnNameTable WHERE COLUMN_NAME = #ColumnName
END
END
END
SET NOCOUNT OFF
IF OBJECT_ID('tempdb..#Abd_tmptbl') IS NOT NULL DROP TABLE #Abd_tmptbl
CREATE TABLE #Abd_tmptbl (TableNameA nvarchar(128), ColumnNameA nvarchar(128), ColumnValueA nvarchar(max),ColumnTypeA nvarchar(20), Count int)
INSERT INTO #Abd_tmptbl
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
DECLARE #Tableee VARCHAR(20), #Columnee varchar(20), #Constraint varchar(20)
DECLARE #items TABLE(tabl int, clmn int)
Create Table #PK_tbl (PK_Col varchar (10))
WHILE EXISTS (select TOP 1 TableNameA FROM #Abd_tmptbl)
BEGIN
SELECT TOP 1 #Tableee = TableNameA, #Columnee = ColumnNameA
------------ GET All PKs of the Table ---------------------
DECLARE #PK_sql varchar(max) = N'INSERT INTO #PK_tbl(PK_Col)
(SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name AND Constraint_Type = "PRIMARY KEY" AND Col.Table_Name = ' + #Tableee +')'
EXEC (#PK_sql)
------------------------------------------------------------
------------ GET CONTRAINT Name ----------------------------
SET #Constraint = N'SELECT name FROM sys.key_constraints WHERE type = "PK" AND OBJECT_NAME(parent_object_id) = ' + #Columnee
------------------------------------------------------------
------------ RELEASE Table From CONSTRAINTS ----------------
DECLARE #REL_tbl VARCHAR(max) = N'ALTER TABLE' + #Tableee +'DROP CONSTRAINT'+ #Constraint
EXEC (#REL_tbl)
------------------------------------------------------------
DECLARE #Update_tbl VARCHAR(max) = N'UPDATE '+ #Tableee + 'SET ' + #Columnee + '=' + #NewValueInt+ ' WHERE' + #Columnee + '=' + #SearchStrColumnValue
EXEC (#Update_tbl)
DECLARE #Sealing_tbl VARCHAR(max) = N'ALTER TABLE' + #Tableee + 'ADD CONSTRAINT' + #Constraint + 'PRIMARY KEY CLUSTERED (SELECT * FROM #PK_tbl)'
EXEC (#Update_tbl)
END

Incorrect syntax near keyword IF dynamic sql

I'm currently new to sql server.
I am using stored procedure with the help of visual studio 2010 express.
And i am experimenting on stored procedure in sql server when i found this error, which is very annoying :
Incorrect syntax near keyword 'IF
UPDATE [table_name]
SET
[delete_datetime] = CURRENT_TIMESTAMP,
[delete_user_record_id] = 2
WHERE [table_name].[record_id] = 2
Here's my stored procedure function. It is to update time stamps on my current table :
USE [MGroupIS]
GO
/****** Object: StoredProcedure [dbo].[iSP_SET_DATA_INFORMATION] Script Date: 02/01/2016 14:40:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_SET_DATA_INFORMATION]
--Paramateres
AS
DECLARE #sql AS NVARCHAR(4000)
DECLARE #pFlag AS VARCHAR(6)
SET #pFlag = #flag
--IF Delete
IF #pFlag = 'DELETE'
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + CHAR(13) +
' SET ' + CHAR(13) +
' [delete_datetime] = CURRENT_TIMESTAMP, ' + CHAR(13) +
' [delete_user_record_id] = ' + CAST(#userRecordID AS VARCHAR(20)) + CHAR(13) +
' WHERE [' + #tableName + '].[' + #keyField + '] = ' + CAST(#recordID AS VARCHAR(20))
END
ELSE
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + CHAR(13) +
' SET ' + CHAR(13) +
' [edit_datetime] = CURRENT_TIMESTAMP, ' + CHAR(13) +
' [edit_user_record_id] = ' + CAST(#userRecordID AS CHAR(3))
END
EXEC sp_executeSQL #sql
PRINT #sql
And i call the stored procedure from another stored procedure (ISP_CFG_ACCESS_RIGHT_QUERY) :
ELSE IF #action = 'SAVE'
--SAVE Action
BEGIN
--If saved
IF #removeUnsaved = 0
BEGIN
UPDATE [CFG_ACCESS_RIGHT]
SET [CFG_ACCESS_RIGHT].[NAME] = '' + #name + '',
[CFG_ACCESS_RIGHT].[NOTE] = '' + #note + ''
WHERE [CFG_ACCESS_RIGHT].[RECORD_ID] = #recordID
DELETE FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [CFG_ACCESS_RIGHT_DETAIL].[access_right_record_id] = #recordID
SET #sql = 'INSERT INTO [CFG_ACCESS_RIGHT_DETAIL] ' + CHAR(13) +
'SELECT * FROM [' + #tempTable + '] ' + CHAR(13) +
' WHERE [' + #tempTable + '].[delete_datetime] IS NULL;'
EXEC sp_executeSQL #sql
EXEC [ISP_SET_DATA_INFORMATION]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
EXEC [ISP_SET_DATA_INFORMATION]
'CFG_ACCESS_RIGHT_DETAIL',
'access_right_record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
END
--If leave without saving
ELSE
BEGIN
EXEC [ISP_SET_DATA_INFORMATION]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
'DELETE',
0
END
Please help.
Thank you before hand.
Edit 1 : Isolating the potential problematic part. Please help
Your dynamic DROP table statement in procedure is syntactically wrong.
It should be like this,
IF OBJECT_ID('tablename', 'U') IS NOT NULL
DROP TABLE tablename;
In addition to that there are few syntax errors in your T-SQL too. I have fixed it.
Please refer this code,
IF #pFlag = 'DELETE'
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + Char(13)
+ ' SET ' + Char(13)
+ ' [delete_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + ' [delete_user_record_id] = '
+ Cast(#userRecordID AS VARCHAR(20))
+ Char(13) + ' WHERE [' + #tableName + '].['
+ #keyField + '] = '
+ Cast(#recordID AS VARCHAR(20))
END
ELSE
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + Char(13)
+ ' SET ' + Char(13)
+ ' [edit_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + ' [edit_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3))
--IF New Record
IF #flag = 'NEW'
BEGIN
SET #sql = #sql + ', ' + Char(13)
+ '[create_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + '[create_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3))
END
--IF Void Record
IF #voidStatus = 1
BEGIN
SET #sql = #sql + ', ' + Char(13) + '[void_status] = 1, '
+ Char(13)
+ '[void_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + '[void_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3)) + ', '
+ Char(13) + '[void_reason] = ''' + #voidReason
+ ''''
END
ELSE
BEGIN
SET #sql = #sql + ', ' + Char(13) + '[void_status] = 0, '
+ Char(13) + '[void_datetime] = NULL, '
+ Char(13) + '[void_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3)) + ', '
+ Char(13) + '[void_reason] = NULL'
END
--IF Print
IF #printed = 1
BEGIN
SET #sql = #sql + ', ' + Char(13)
+ '[print_count] = [print_count] + 1, '
+ Char(13) + '[last_print_datetime] = NULL, '
+ Char(13) + '[print_user_record_id] = 0'
+ Cast(#userRecordID AS CHAR(3))
END
SET #sql = #sql + ', ' + Char(13)
+ 'record_version = record_version + 1 '
+ Char(13) + ' WHERE [' + #tableName + '].['
+ #keyField + '] = '
+ Cast(#recordID AS VARCHAR(20))
END
EXEC Sp_executesql
#sql
PRINT #sql
Procedure Code:
ALTER PROCEDURE [dbo].[Sp_cfg_access_right_query] #recordID INT,
#userRecordID INT,
#action CHAR(4),
#flag CHAR(6),
#tempTable VARCHAR(50),
#name VARCHAR(50),
#note VARCHAR(1000),
#voidStatus BIT,
#voidReason VARCHAR(200),
#removeUnsaved BIT
AS
--Setting NULL values
SET #recordID = Isnull(#recordID, 0)
SET #userRecordID = Isnull(#recordID, 0)
SET #action = Isnull(#action, '')
SET #flag = Isnull(#flag, '')
SET #tempTable = Isnull(#tempTable, '')
SET #name = Isnull(#name, '')
SET #note = Isnull(#note, '')
SET #voidStatus = Isnull(#voidStatus, 0)
SET #voidReason = Isnull(#voidReason, '')
DECLARE #detailCount INT
DECLARE #currentID INT
DECLARE #sql NVARCHAR(1000)
DECLARE #temp VARCHAR(100)
DECLARE #tempConstraint VARCHAR(100)
IF #action = 'LOAD'
--LOAD action
BEGIN
SET #temp = 'CFG_TEMP_ARD_'
+ Replace(Cast(Newid() AS VARCHAR(50)), '-', '')
SET #tempConstraint = Cast(Year(CURRENT_TIMESTAMP) AS VARCHAR(4))
+ Cast(Month(CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Day(CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(HOUR, CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(MINUTE, CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(SECOND, CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(MILLISECOND, CURRENT_TIMESTAMP) AS VARCHAR(3))
SET #sql = 'SELECT * INTO [' + #temp
+ '] FROM [CFG_ACCESS_RIGHT_DETAIL] WHERE 1=0;'
EXEC Sp_executesql
#sql
SET #sql = 'ALTER TABLE [' + #temp + '] ' + Char(13)
+ 'ADD CONSTRAINT PK_' + #tempConstraint
+ Char(13)
+ 'PRIMARY KEY ([record_id], [access_right_record_id]);'
EXEC Sp_executesql
#sql
IF #flag = 'NEW'
BEGIN
INSERT INTO [CFG_ACCESS_RIGHT]
(NAME,
note,
record_version)
VALUES ('',
'',
1)
SELECT #recordID = Scope_identity()
FROM [CFG_ACCESS_RIGHT];
END
SELECT #recordID currentID,
#temp tempTable
--Load Access Right
SELECT *
FROM [CFG_ACCESS_RIGHT]
WHERE [record_id] = #recordID
--Check & Return Detail Count
SELECT #detailCount = ##ROWCOUNT
FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [access_right_record_id] = #recordID
SELECT Isnull(#detailCount, 0) detailCount
--Load Access Right Details if exist
IF #detailCount > 0
BEGIN
SELECT *
FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [access_right_record_id] = #recordID
AND [delete_datetime] IS NULL
END
END
ELSE IF #action = 'SAVE'
--SAVE Action
BEGIN
--If saved
IF #removeUnsaved = 0
BEGIN
UPDATE [CFG_ACCESS_RIGHT]
SET [CFG_ACCESS_RIGHT].[NAME] = '' + #name + '',
[CFG_ACCESS_RIGHT].[NOTE] = '' + #note + ''
WHERE [CFG_ACCESS_RIGHT].[RECORD_ID] = #recordID
DELETE FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [CFG_ACCESS_RIGHT_DETAIL].[access_right_record_id] = #recordID
SET #sql = 'INSERT INTO [CFG_ACCESS_RIGHT_DETAIL] '
+ Char(13) + 'SELECT * FROM [' + #tempTable + '] '
+ Char(13) + ' WHERE [' + #tempTable
+ '].[delete_datetime] IS NULL;'
EXEC Sp_executesql
#sql
EXEC [Sp_set_data_information]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
EXEC [Sp_set_data_information]
'CFG_ACCESS_RIGHT_DETAIL',
'access_right_record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
END
--If leave without saving
ELSE
BEGIN
EXEC [Sp_set_data_information]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
'DELETE',
0
END
END
SET #sql ='IF OBJECT_ID(''' + #tempTable
+ ''', ''U'') IS NOT NULL
DROP TABLE ' + #tempTable
EXEC Sp_executesql
#sql

How to display no Data message in Stored procedre

If #MeasureRuleTrendId value has no data i need to display either empty table or No Data message.. Can you please help what we need to add in the below code... Thanks in Advance
ALTER PROCEDURE [dbo].[uspRptDQMeasureDetail] (#MeasureRuleTrendId INT)
AS
BEGIN
SET NOCOUNT ON
truncate table dq.tt
IF OBJECT_ID('tempdb..#columns') IS NOT NULL
DROP TABLE #columns
IF OBJECT_ID('tempdb..##Tmp') IS NOT NULL
DROP TABLE ##Tmp
CREATE TABLE #Columns (
Id INT IDENTITY
,Col VARCHAR(500)
)
DECLARE #RowsToProcess AS INT
DECLARE #CurrentRow AS INT
DECLARE #SQL AS VARCHAR(MAX)
DECLARE #xml AS XML
DECLARE #Col AS VARCHAR(100)
DECLARE #SQLUnpivot AS VARCHAR(MAX)
DECLARE #SQLTempTable AS VARCHAR(MAX)
SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl
WHERE [MeasureRuleTrendId] = #MeasureRuleTrendId
SET #SQL = 'DECLARE #xml AS XML; SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl where[MeasureRuleTrendId] = ' + Convert(VARCHAR(100), #MeasureRuleTrendId) + '; INSERT INTO ##Tmp Select '
SET #SQLUnpivot = 'SELECT ID, ColName, VAL FROM (SELECT * from ##Tmp ) p UNPIVOT (VAL FOR ColName IN ('
SET #SQLTempTable = ''
SET #SQLTempTable = 'CREATE Table ##Tmp ( ID INT Identity ,'
INSERT INTO #Columns (col)
SELECT DISTINCT C.value('local-name(.)', 'varchar(50)') AS NodeName
FROM #xml.nodes('/row/*') AS T(C)
SET #RowsToProcess = ##ROWCOUNT
SET #CurrentRow = 0
WHILE #CurrentRow < #RowsToProcess
BEGIN
SET #CurrentRow = #CurrentRow + 1
SELECT #Col = Col
FROM #Columns
WHERE ID = #CurrentRow
SET #sql = #SQL + #col + ' = Events.value(' + '''' + '(' + #col + ')[1]' + '''' + ',' + '''' + 'varchar(max)' + '''' + ')'
SET #SQLTempTable = #SQLTempTable + #Col + ' VARCHAR(max)'
SET #SQLUnpivot = #SQLUnpivot + #Col
IF #CurrentRow = #RowsToProcess
BEGIN
SET #sql = #sql + ' '
SET #SQLTempTable = #SQLTempTable + ' '
SET #SQLUnpivot = #SQLUnpivot + ' '
END
ELSE
BEGIN
SET #sql = #sql + ' , '
SET #SQLTempTable = #SQLTempTable + ' , '
SET #SQLUnpivot = #SQLUnpivot + ' , '
END
END
SET #SQL = #sql + + ' FROM #xml.nodes(''/row'') AS XTbl(Events)'
SET #SQLUnpivot = #SQLUnpivot + '))AS unpvt'
set #SQLUnpivot = 'insert into dq.tt ' + #SQLUnpivot
SET #SQLTempTable = #SQLTempTable + ')'
EXECUTE (#SQLTempTable)
EXECUTE (#SQL)
Print #sqlunpivot
EXECUTE (#SQLUnpivot)
SELECT * from dq.tt
SET NOCOUNT OFF
END
It should be enough to add this in your final WHERE, if this is a question of performance, you could add the WHERE to your dynamic SQL too:
ALTER PROCEDURE [dbo].[uspRptDQMeasureDetail] (#MeasureRuleTrendId INT)
AS
BEGIN
SET NOCOUNT ON
truncate table dq.tt
IF OBJECT_ID('tempdb..#columns') IS NOT NULL
DROP TABLE #columns
IF OBJECT_ID('tempdb..##Tmp') IS NOT NULL
DROP TABLE ##Tmp
CREATE TABLE #Columns (
Id INT IDENTITY
,Col VARCHAR(500)
)
DECLARE #RowsToProcess AS INT
DECLARE #CurrentRow AS INT
DECLARE #SQL AS VARCHAR(MAX)
DECLARE #xml AS XML
DECLARE #Col AS VARCHAR(100)
DECLARE #SQLUnpivot AS VARCHAR(MAX)
DECLARE #SQLTempTable AS VARCHAR(MAX)
SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl
WHERE [MeasureRuleTrendId] = #MeasureRuleTrendId
SET #SQL = 'DECLARE #xml AS XML; SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl where[MeasureRuleTrendId] = ' + Convert(VARCHAR(100), #MeasureRuleTrendId) + '; INSERT INTO ##Tmp Select '
SET #SQLUnpivot = 'SELECT ID, ColName, VAL FROM (SELECT * from ##Tmp ) p UNPIVOT (VAL FOR ColName IN ('
SET #SQLTempTable = ''
SET #SQLTempTable = 'CREATE Table ##Tmp ( ID INT Identity ,'
INSERT INTO #Columns (col)
SELECT DISTINCT C.value('local-name(.)', 'varchar(50)') AS NodeName
FROM #xml.nodes('/row/*') AS T(C)
SET #RowsToProcess = ##ROWCOUNT
SET #CurrentRow = 0
WHILE #CurrentRow < #RowsToProcess
BEGIN
SET #CurrentRow = #CurrentRow + 1
SELECT #Col = Col
FROM #Columns
WHERE ID = #CurrentRow
SET #sql = #SQL + #col + ' = Events.value(' + '''' + '(' + #col + ')[1]' + '''' + ',' + '''' + 'varchar(max)' + '''' + ')'
SET #SQLTempTable = #SQLTempTable + #Col + ' VARCHAR(max)'
SET #SQLUnpivot = #SQLUnpivot + #Col
IF #CurrentRow = #RowsToProcess
BEGIN
SET #sql = #sql + ' '
SET #SQLTempTable = #SQLTempTable + ' '
SET #SQLUnpivot = #SQLUnpivot + ' '
END
ELSE
BEGIN
SET #sql = #sql + ' , '
SET #SQLTempTable = #SQLTempTable + ' , '
SET #SQLUnpivot = #SQLUnpivot + ' , '
END
END
SET #SQL = #sql + + ' FROM #xml.nodes(''/row'') AS XTbl(Events)'
SET #SQLUnpivot = #SQLUnpivot + '))AS unpvt'
set #SQLUnpivot = 'insert into dq.tt ' + #SQLUnpivot
SET #SQLTempTable = #SQLTempTable + ')'
EXECUTE (#SQLTempTable)
EXECUTE (#SQL)
Print #sqlunpivot
EXECUTE (#SQLUnpivot)
--Added your parameter with WHERE...
SELECT * from dq.tt WHERE #MeasureRuleTrendId IS NOT NULL
SET NOCOUNT OFF
END

Incremental batch delete and insert actions very slow in SQL Server

I have the following stored procedure which deletes and inserts rows in a table. It is running slow.
I have read various proposals and i have implemented:
Delete rows in batches and using derived table
Disable FK
Indexes on fields that are in the where clause.
So the way it should go is:
Tables have around 10 million records.
Every day i need to refresh around 15-30% of them. I use this SP to do it.
Source:
CREATE PROCEDURE [dbo].[spIncrementalUpdate]
-- Add the parameters for the stored procedure here
#table_inc nvarchar(30),
#table_target nvarchar(30),
#table_date nvarchar(30),
#field1 nvarchar(10),
#field2 nvarchar(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #logmessage as nvarchar(2048)
DECLARE #logdatacode as int
DECLARE #cmd as nvarchar(max)
DECLARE #fromjulian nvarchar(10)
DECLARE #datadate datetime
DECLARE #datadate_str nvarchar(10)
DECLARE #rows int
DECLARE #ParmDefinition nvarchar(500)
select #fromjulian = '114000'
print 'Using ' + #fromjulian
--
-- GET THE ROW COUNT OF THE INC TABLE.
--
IF #field2 = ''
BEGIN
SET #cmd = N'SELECT #retval = count(*) from ' +
#table_inc + ' where ' + #field1 +' > ' + #fromjulian
END
ELSE
BEGIN
SET #cmd = N'SELECT #retval = count(*) from ' +
#table_inc + ' where ' + #field1 +' > ' + #fromjulian +
' OR ' + #field2 +' > ' + #fromjulian
END
SET #ParmDefinition = N'#retval int OUTPUT'
EXEC sp_executesql #cmd, #ParmDefinition, #retval = #rows OUTPUT
--
if #rows <> 0
BEGIN
SET #logmessage = #table_inc + ' has ' +
cast(#rows as nvarchar(10)) +
' rows after ' + #fromjulian + ', deleting'
SET #logdatacode = 1000
--
-- Delete the records from original table based on #fromjulian
--
IF #field2 = ''
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' + #table_target +
' where ' + #field1 + ' > ' + #fromjulian +
' order by ' + #field1 + ') ' +
#table_target
print #cmd
END
ELSE
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' +
#table_target +
' where ' + #field1 + ' > ' + #fromjulian +
' OR ' + #field2 +' > ' + #fromjulian +
' order by ' + #field1 + ',' + #field2 + ') ' +
#table_target
print #cmd
END
SELECT 1
WHILE ##ROWCOUNT <> 0
BEGIN
EXEC sp_executesql #cmd
END
--
-- Inserting the records to target from INC table
--
IF #field2 = ''
BEGIN
SET #cmd = N'insert into ' + #table_target +
' select * from ' + #table_inc +
' where ' + #field1 +' > ' + cast(#fromjulian as nvarchar(10))
print #cmd
END
ELSE
BEGIN
SET #cmd = N'insert into ' + #table_target +
' select * from ' + #table_inc +
' where ' + #field1 +' > ' + cast(#fromjulian as nvarchar(10)) +
' OR ' + #field2 +' > ' + cast(#fromjulian as nvarchar(10))
print #cmd
END
print #cmd
EXEC sp_executesql #cmd
END
ELSE
BEGIN
SET #logmessage = 'NO ROWS IN ' + #table_inc + ' AFTER ' + cast(#fromjulian as nvarchar(10))
SET #logdatacode = 1001
END
--
-- LOG
--
INSERT INTO YLA_GROUP.[dbo].[sysssislog]
([event]
,[computer]
,[operator]
,[source]
,[sourceid]
,[executionid]
,[starttime]
,[endtime]
,[datacode]
,[databytes]
,[message])
VALUES
('spIncrementalUpdate','','','',NEWID(),NEWID(),getdate(),getdate(),#logdatacode,null,#logmessage)
print cast(#logdatacode as nvarchar(10)) + ' - ' + #logmessage
END
Since you are deleting rows in batches, you should remove the ORDER BY clause from your subquery because it is not necessary.
Here's the extract from your script:
IF #field2 = ''
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' + #table_target +
' where ' + #field1 + ' > ' + #fromjulian + ') ' + #table_target
print #cmd
END
ELSE
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' + #table_target +
' where ' + #field1 + ' > ' + #fromjulian +
' OR ' + #field2 +' > ' + #fromjulian + ') ' + #table_target
print #cmd
END
Remember that sorting can be an expensive operation, and even more expensive if you remove (correctly in this case) indexes.
Beyond that, there's not much you can do. Also consider that using dynamic SQL, execution plans are not cached. So, every time you execute the command inside #cmd the Query Engine needs to calculate the optimal execution plan. Unfortunately, as far as I can see, you need dynamic SQL.

Stored Procedure not Working according to need

What am I doing wrong? My stored procedure is not working according to need when using =, >, < as a parameter please help
Here is my stored procedure:
ALTER PROCEDURE [dbo].[storedp_Search]
#pAccountTypeId int = null,
#pFirstName varchar(25) = null,
#pLastName varchar(35) = null,
#pZip varchar(10) = null,
#pOperator varchar(2) = null,
#pRating varchar(2) = null
AS
BEGIN
SET NOCOUNT ON;
Declare #SQLQuery AS NVarchar(4000)
SET #SQLQuery = 'select
at.AccountName,
U.UserId, U.FirstName, U.LastName,
U.NMLS, U.[Address], U.PrimaryEmailId As Office,
U.AdditionalEmail As Personal,
U.DirectPhone As Work, U.Mobile,
R.RatingStar
from
[User] U
left outer join
RatingReview R on R.UserId = U.UserId
left outer join
AccountType at on at.AccountTypeId = U.AccountTypeId
where U.Deleted = 0
AND at.AccountTypeId = '+CAST(#pAccountTypeId as Varchar(10))+'
AND U.FirstName = ''' + #pFirstName + '''
AND U.LastName = ''' + #pLastName + '''
AND U.Zip = ''' + #pZip + '''
AND R.RatingStar = ''' + #pRating + ''''
IF(#pAccountTypeId != null OR #pAccountTypeId != '')
BEGIN
SET #SQLQuery = #SQLQuery + ' AND at.AccountTypeId='+CONVERT(VARCHAR, #pAccountTypeId )
END
IF(#pFirstName != null OR #pFirstName != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.FirstName Like ''%' + #pFirstName + '%'''
END
IF(#pLastName !=null OR #pLastName != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.LastName Like ''%' + #pLastName + '%'''
END
IF(#pZip !=null OR #pZip != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.Zip Like ''%' + #pZip + '%'''
END
IF(#pOperator = '=')
BEGIN
SET #SQLQuery += ' AND r.ratingstar = ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
IF(#pOperator = '>')
BEGIN
SET #SQLQuery += ' AND r.ratingstar < ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
IF(#pOperator = '<')
BEGIN
SET #SQLQuery += ' AND r.ratingstar > ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
SET #SQLQuery=#SQLQuery+
'group by
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId,
U.AdditionalEmail,
U.DirectPhone,
U.Mobile,
R.RatingStar'
EXEC (#SQLQuery)
END
when i am using following exec statement its working fine
Execute storedp_Search 1,'Mark','Smith','48393','=','5'
but when using the same with different conditions then its not working.
Execute storedp_Search 1,'Mark','Smith','48393','>','4'
Try this,
I think you misspelled the operator inside the if condition, if i'm not wrong
ALTER PROCEDURE [dbo].[Storedp_Search] #pAccountTypeId INT =NULL,
#pFirstName VARCHAR(25)=NULL,
#pLastName VARCHAR(35)=NULL,
#pZip VARCHAR(10)=NULL,
#pOperator VARCHAR(2)=NULL,
#pRating VARCHAR(2)=NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQLQuery AS NVARCHAR(4000)
SET #SQLQuery= 'select
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId As Office,
U.AdditionalEmail As Personal,
U.DirectPhone As Work,
U.Mobile,
R.RatingStar
from [User] U
left outer join RatingReview R on R.UserId =U.UserId
left outer join AccountType at on at.AccountTypeId = U.AccountTypeId
where U.Deleted =0
AND at.AccountTypeId = '
+ Cast(#pAccountTypeId AS VARCHAR(10))
+ '
AND U.FirstName = ''' + #pFirstName
+ '''
AND U.LastName = ''' + #pLastName
+ '''
AND U.Zip = ''' + #pZip
+ '''
AND R.RatingStar = ''' + #pRating + ''''
IF( #pAccountTypeId IS NOT NULL
OR #pAccountTypeId != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND at.AccountTypeId='
+ CONVERT(VARCHAR, #pAccountTypeId )
END
IF( #pFirstName IS NOT NULL
OR #pFirstName != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.FirstName Like ''%'
+ #pFirstName + '%'''
END
IF( #pLastName IS NOT NULL
OR #pLastName != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.LastName Like ''%'
+ #pLastName + '%'''
END
IF( #pZip IS NOT NULL
OR #pZip != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.Zip Like ''%' + #pZip + '%'''
END
IF( #pOperator = '=' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar = '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
IF( #pOperator = '>' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar > '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
IF( #pOperator = '<' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar < '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
SET #SQLQuery=#SQLQuery + 'group by
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId,
U.AdditionalEmail,
U.DirectPhone,
U.Mobile,
R.RatingStar'
EXEC ( #SQLQuery )
END

Resources