how to change table name dynamically when joining stored procedure run - sql-server

I want to make a sql stored procedure and use it as the datasource of crystal report. i made it as follows and it works fine as i want.
CREATE PROCEDURE [dbo].[sp_ScanPointPrint]
#branch varchar(50),
#tripID int,
#scanPoint varchar(50)
AS
BEGIN
SET NOCOUNT ON;
select sp.BranchCode, sp.ScanPoint, sp.TripId, sp.DoneBy,FORMAT(sp.DateTime,'dd MMMM, yyyy hh:mm tt'), sp.Driver, sp.CarNo, sp.ItemShouldBe, sp.ActualTaken, sp.MissedAny, sp.MissedCount, sp.TookExtra, sp.ExtraCount, spT.OrderNo,spt.ItemBarcode, oi.ItemName
from ScanPointLog as sp
left join TableScanPoint1 as spT on sp.BranchCode = spT.BranchCode and sp.TripId = spT.TripId
left join OrderItem as Oi on spt.OrderNo=oi.OrderNO and spt.ItemBarcode=oi.ItemBarcode
where sp.BranchCode=#branch and sp.ScanPoint=#scanPoint and spt.IsItem=1 and sp.TripId=#tripID
END
GO
what I want to perform and i am unable to do is changing the TableScanPoint1 table name to another table name. there are 8 tables as TableScanPoint1 to TableScanePont8 with same structure but different data in them. the purpose to do this make one report design use it as the end user wants. the end user will choose table, branch, tripid and scanpoint from vb.net application at run time.
can anyone please help me on this ?
thanks

CREATE PROCEDURE [dbo].[sp_ScanPointPrint]
#branch varchar(50),
#tripID int,
#scanPoint varchar(50),
#tablenametoscan varchar(200)
AS
BEGIN
SET NOCOUNT ON;
declare #sqltoexecute varchar(max)
set #sqltoexecute = '
select sp.BranchCode, sp.ScanPoint, sp.TripId, sp.DoneBy,FORMAT(sp.DateTime,'dd MMMM, yyyy hh:mm tt'), sp.Driver, sp.CarNo, sp.ItemShouldBe, sp.ActualTaken, sp.MissedAny, sp.MissedCount, sp.TookExtra, sp.ExtraCount, spT.OrderNo,spt.ItemBarcode, oi.ItemName
from ScanPointLog as sp
left join ' + #tablenametoscan + ' as spT on sp.BranchCode = spT.BranchCode and sp.TripId = spT.TripId
left join OrderItem as Oi on spt.OrderNo=oi.OrderNO and spt.ItemBarcode=oi.ItemBarcode
where sp.BranchCode=#branch and sp.ScanPoint=#scanPoint and spt.IsItem=1 and sp.TripId=#tripID '
exec sp_executesql #sqltoexecute
END
GO

Please try to make use of below query:
CREATE PROCEDURE [dbo].[sp_ScanPointPrint]
#branch VARCHAR(50),
#tripID INT,
#scanPoint VARCHAR(50),
#table VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #query NVARCHAR(max)
SET #query = '
select sp.BranchCode, sp.ScanPoint, sp.TripId, sp.DoneBy,FORMAT(sp.DateTime,''dd MMMM, yyyy hh:mm tt''), sp.Driver, sp.CarNo, sp.ItemShouldBe, sp.ActualTaken, sp.MissedAny, sp.MissedCount, sp.TookExtra, sp.ExtraCount, spT.OrderNo,spt.ItemBarcode, oi.ItemName
from ScanPointLog as sp
left join ' + #table + ' as spT on sp.BranchCode = spT.BranchCode and sp.TripId = spT.TripId
left join OrderItem as Oi on spt.OrderNo=oi.OrderNO and spt.ItemBarcode=oi.ItemBarcode
where sp.BranchCode=#branch and sp.ScanPoint=#scanPoint and spt.IsItem=1 and sp.TripId=#tripID '
EXEC (#query)
END
GO

Related

combine #sql query with temp table in SQL [duplicate]

In my stored procedure I declared two table variables on top of my procedure. Now I am trying to use that table variable within a dynamic sql statement but I get this error at the time of execution of that procedure. I am using Sql Server 2008.
This is how my query looks like,
set #col_name = 'Assoc_Item_'
+ Convert(nvarchar(2), #curr_row1);
set #sqlstat = 'update #RelPro set '
+ #col_name
+ ' = (Select relsku From #TSku Where tid = '
+ Convert(nvarchar(2), #curr_row1) + ') Where RowID = '
+ Convert(nvarchar(2), #curr_row);
Exec(#sqlstat);
And I get the following errors,
Must declare the table variable "#RelPro".
Must declare the table variable "#TSku".
I have tried to take the table outside of the string block of dynamic query but to no avail.
On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.
So from the code you posted you could use this approach for #TSku but not for #RelPro
Example syntax below.
CREATE TYPE MyTable AS TABLE
(
Foo int,
Bar int
);
GO
DECLARE #T AS MyTable;
INSERT INTO #T VALUES (1,2), (2,3)
SELECT *,
sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM #T
EXEC sp_executesql
N'SELECT *,
sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM #T',
N'#T MyTable READONLY',
#T=#T
The physloc column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.
Your EXEC executes in a different context, therefore it is not aware of any variables that have been declared in your original context. You should be able to use a temp table instead of a table variable as shown in the simple demo below.
create table #t (id int)
declare #value nchar(1)
set #value = N'1'
declare #sql nvarchar(max)
set #sql = N'insert into #t (id) values (' + #value + N')'
exec (#sql)
select * from #t
drop table #t
You don't have to use dynamic SQL
update
R
set
Assoc_Item_1 = CASE WHEN #curr_row = 1 THEN foo.relsku ELSE Assoc_Item_1 END,
Assoc_Item_2 = CASE WHEN #curr_row = 2 THEN foo.relsku ELSE Assoc_Item_2 END,
Assoc_Item_3 = CASE WHEN #curr_row = 3 THEN foo.relsku ELSE Assoc_Item_3 END,
Assoc_Item_4 = CASE WHEN #curr_row = 4 THEN foo.relsku ELSE Assoc_Item_4 END,
Assoc_Item_5 = CASE WHEN #curr_row = 5 THEN foo.relsku ELSE Assoc_Item_5 END,
...
from
(Select relsku From #TSku Where tid = #curr_row1) foo
CROSS JOIN
#RelPro R
Where
R.RowID = #curr_row;
You can't do this because the table variables are out of scope.
You would have to declare the table variable inside the dynamic SQL statement or create temporary tables.
I would suggest you read this excellent article on dynamic SQL.
http://www.sommarskog.se/dynamic_sql.html
Well, I figured out the way and thought to share with the people out there who might run into the same problem.
Let me start with the problem I had been facing,
I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.
Solution:
I simply changed them to Global Temporary Variables and they worked.
Find my stored procedure underneath.
CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
#PRODUCT_SKU nvarchar(15) = Null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
DROP TABLE ##RelPro
END
Create Table ##RelPro
(
RowID int identity(1,1),
ID int,
Item_Name nvarchar(max),
SKU nvarchar(max),
Vendor nvarchar(max),
Product_Img_180 nvarchar(max),
rpGroup int,
Assoc_Item_1 nvarchar(max),
Assoc_Item_2 nvarchar(max),
Assoc_Item_3 nvarchar(max),
Assoc_Item_4 nvarchar(max),
Assoc_Item_5 nvarchar(max),
Assoc_Item_6 nvarchar(max),
Assoc_Item_7 nvarchar(max),
Assoc_Item_8 nvarchar(max),
Assoc_Item_9 nvarchar(max),
Assoc_Item_10 nvarchar(max)
);
Begin
Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)
Select distinct zp.ProductID, zp.Name, zp.SKU,
(Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
'http://s0001.server.com/is/sw11/DG/' +
(Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
'_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When #PRODUCT_SKU Is Not Null Then #PRODUCT_SKU Else zp.SKU End)
End
declare #curr_row int = 0,
#tot_rows int= 0,
#sku nvarchar(15) = null;
IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));
Select #curr_row = (Select MIN(RowId) From ##RelPro);
Select #tot_rows = (Select MAX(RowId) From ##RelPro);
while #curr_row <= #tot_rows
Begin
select #sku = SKU from ##RelPro where RowID = #curr_row;
truncate table ##TSku;
Insert ##TSku(relsku)
Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN
[INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = #sku)
declare #curr_row1 int = (Select Min(tid) From ##TSku),
#tot_rows1 int = (Select Max(tid) From ##TSku);
If(#tot_rows1 <> 0)
Begin
While #curr_row1 <= #tot_rows1
Begin
declare #col_name nvarchar(15) = null,
#sqlstat nvarchar(500) = null;
set #col_name = 'Assoc_Item_' + Convert(nvarchar(2), #curr_row1);
set #sqlstat = 'update ##RelPro set ' + #col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), #curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), #curr_row);
Exec(#sqlstat);
set #curr_row1 = #curr_row1 + 1;
End
End
set #curr_row = #curr_row + 1;
End
Select * From ##RelPro;
END
GO
I don't think that is possible (though refer to the update below); as far as I know a table variable only exists within the scope that declared it. You can, however, use a temp table (use the create table syntax and prefix your table name with the # symbol), and that will be accessible within both the scope that creates it and the scope of your dynamic statement.
UPDATE: Refer to Martin Smith's answer for how to use a table-valued parameter to pass a table variable in to a dynamic SQL statement. Also note the limitation mentioned: table-valued parameters are read-only.
Here is an example of using a dynamic T-SQL query and then extracting the results should you have more than one column of returned values (notice the dynamic table name):
DECLARE
#strSQLMain nvarchar(1000),
#recAPD_number_key char(10),
#Census_sub_code varchar(1),
#recAPD_field_name char(100),
#recAPD_table_name char(100),
#NUMBER_KEY varchar(10),
if object_id('[Permits].[dbo].[myTempAPD_Txt]') is not null
DROP TABLE [Permits].[dbo].[myTempAPD_Txt]
CREATE TABLE [Permits].[dbo].[myTempAPD_Txt]
(
[MyCol1] char(10) NULL,
[MyCol2] char(1) NULL,
)
-- an example of what #strSQLMain is : #strSQLMain = SELECT #recAPD_number_key = [NUMBER_KEY], #Census_sub_code=TEXT_029 FROM APD_TXT0 WHERE Number_Key = '01-7212'
SET #strSQLMain = ('INSERT INTO myTempAPD_Txt SELECT [NUMBER_KEY], '+ rtrim(#recAPD_field_name) +' FROM '+ rtrim(#recAPD_table_name) + ' WHERE Number_Key = '''+ rtrim(#Number_Key) +'''')
EXEC (#strSQLMain)
SELECT #recAPD_number_key = MyCol1, #Census_sub_code = MyCol2 from [Permits].[dbo].[myTempAPD_Txt]
DROP TABLE [Permits].[dbo].[myTempAPD_Txt]
Using Temp table solves the problem but I ran into issues using Exec so I went with the following solution of using sp_executesql:
Create TABLE #tempJoin ( Old_ID int, New_ID int);
declare #table_name varchar(128);
declare #strSQL nvarchar(3072);
set #table_name = 'Object';
--build sql sting to execute
set #strSQL='INSERT INTO '+#table_name+' SELECT '+#columns+' FROM #tempJoin CJ
Inner Join '+#table_name+' sourceTbl On CJ.Old_ID = sourceTbl.Object_ID'
**exec sp_executesql #strSQL;**

Get data using same parameter with different values in sql

I need to show multiple record tables using same parameter suppose some ID.
Data has been differ as per that parameter values which is different for all.
I could not understand your requirement. But you can query sys.columns for column names to find the tables which have the same column
select
OBJECT_NAME(object_id) as table_name,
name as column_name
from sys.columns
where
name like N'%id%'
For passsing a list of IDs into a stored procedure, most recent method is using Table Valued Parameters aka TVP
Following is an example for using TVP in SQL Server
First you need to create the type in database. Then you populate the variable of the table type with data. You have to do these in the front end. Then you pass this parameter to your stored procedure
I used databases view for sample, you can use your table and ID column instead
create type IDTableType as table
(
Id int
);
go
create procedure ReadData (
#IdList IDTableType readonly
)
as
select *
from sys.databases as d
inner join #IdList as p
on d.database_id = p.id
go
declare #IDs as IDTableType
insert into #IDs values (1),(5),(3)
exec ReadData #IDs
But maybe the most common usage is with string parameter which is concatenated form of IDs
This time you need a SQL split string function to split input parameter into ID list. You can use the referred sample or use one of the custom split functions on the web. If you are using SQL Server 2016 or later, you can use string_split function, too
create procedure ReadData2 (
#IdList varchar(max)
)
as
select *
from sys.databases as d
inner join dbo.split(#IdList,0,0) as s
on d.database_id = s.val
go
declare #IDs as varchar(max) = '1,3,5,6'
exec ReadData2 #IDs
First thing i make fun in sql:
USE [ZAB_HCTMS]
GO
/****** Object: UserDefinedFunction [dbo].[LCNos] Script Date: 1/8/2019 1:09:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object: UserDefinedTableType [dbo].[oldTVP_ConsignmentNoteLineItems] Script Date: 1/7/2019 1:00:53 PM ******/
ALTER FUNCTION [dbo].[LCNos]
(
#LCNo NVARCHAR(MAX),
#Comma CHAR(1)
)
RETURNS #Output TABLE (
ID NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#LCNo, LEN(#LCNo) - 1, LEN(#LCNo)) <> #Comma
BEGIN
SET #LCNo = #LCNo + #Comma
END
WHILE CHARINDEX(#Comma, #LCNo) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Comma, #LCNo)
INSERT INTO #Output(ID)
SELECT SUBSTRING(#LCNo, #StartIndex, #EndIndex - 1)
SET #LCNo = SUBSTRING(#LCNo, #EndIndex + 1, LEN(#LCNo))
END
RETURN
END
then sp for this:
-- EXEC GetLCsDetails '2188,2196,2201'
alter PROCEDURE GetLCsDetails
#LCNos VARCHAR(100)
AS
BEGIN
SELECT lr.*, lr.PayBalance 'TotalPayBalance', s.Name 'SuppName',
cb.AdvancePayment, s.[Address] 'Address',
s.PinCode, pod.SupplierBillNo
FROM LorryChallans lr
left join ConsignmentBookings cb on lr.ConsignmentBookingID =
cb.ConsignmentBookingID
left join Suppliers s on cb.VehicleSupplierID = s.SupplierID
left join POD pod on lr.ConsignmentBookingID = pod.ConsignmentBookingID
WHERE
lr.LorryChallanNumber
IN( SELECT CAST(ID AS INTEGER) FROM dbo.LCNos(#LCNos, ',') )
END
and finally passing string comma separated ids from jquery:
function chk()
{
$('.Checkbox:checked').map(function () {
return $(this).attr('data-lcno');
}).get().join(',')
}
data-lcno is data attribute to checkboxlist.

How to use table valued parameter with the IN keyword

Edit:
I tried to replace:
#LocationIDs NVARCHAR(MAX) = null,
with
#LocationIDs LocationIdArray READONLY,
but now I get an error saying:
Must declare the scalar variable "#LocationIDs".
--END EDIT--
I have this stored procedure that I need to address:
CREATE PROCEDURE [dbo].[spAP_GetTechnician_Door_Unlock]
#LocationIDs NVARCHAR(MAX) = NULL,
#AlarmDateFrom DATETIME = NULL,
#AlarmDateTo DATETIME = NULL,
#TechnicianID INT = NULL,
#LocationId INT = NULL
AS
BEGIN
IF (#LocationIDs = 'x')
BEGIN
SELECT #LocationIDs = dbo.fn_GetAll_Location_Id()
END
DECLARE #query NVARCHAR(MAX);
SET #query = 'WITH CTE AS (SELECT ROW_NUMBER() OVER(ORDER BY al.Alarm_Log_ID desc)AS RowNumber,
isnull(t.Technician_ID,'''')[Technician_ID], (isnull(t.Last_Name,'''') +'' ''+ isnull(t.Name,'''')) TechnicianName,isnull(t.Emailid,'''') as EmailID,isnull(t.phone,'''') as Phone,dbo.fNAP_DateFormat(al.Alarm_date) as Alarm_date,
Al.Site_ID,s.Name as SiteName,al.point_Address,l.location_Name,l.Location_ID ,shs.StatusData
from z_EntityMast_Alarm_Log al
left join z_EntityMast_Technician t on al.Technician_ID=t.Technician_id
left join z_EntityMast_Site s on s.Site_ID=al.Site_ID
left join z_EntityMast_Location l on s.Location_ID=l.Location_id
left join z_EntityMast_Site_Hardware_Status shs on s.site_id=shs.siteid
left join z_SysVar_Alarm_Type_00004 at on al.Alarm_Type=at.ID
where at.Is_Linkable=1 and al.Alarm_Type !=70'
if(isnull(#LocationId,0)!=0)
set #query=#query+' and s.Location_ID ='+convert(varchar(12),#LocationId);
else
set #query=#query+' and s.Location_ID in ('+#LocationIDs+')';
if(isnull(#AlarmDateFrom,0)!=0 and #AlarmDateFrom !='')
set #query=#query+'and (DATEDIFF(DAY,'''+convert(varchar(30),#AlarmDateFrom)+''', al.Alarm_Date)>=0 and DATEDIFF(DAY,'''+convert(varchar(30),#AlarmDateTo)+''',al.Alarm_Date)<=0)';
if(isnull(#TechnicianID,0)!=0)
set #query=#query+'and t.Technician_ID ='+ convert(varchar(10),#TechnicianID);
set #query=#query + ')';
set #query=#query +'select * from CTE ';
-- PRINT #query
EXEC (#query)
END
I need to optimize it and I have to use table valued parameters for the LocationIds parameter, instead of it using NVARCHAR(MAX).
The problem is in this line of code:
SET #query = #query + ' and s.Location_ID in ('+#LocationIDs+')';
My question is: how does one replace that line of code and replace it with a table valued parameter in such a way that the concatenation would still work?
Thanks!
SET #query = #query + ' and s.Location_ID in ('+#LocationIDs+')';
My question is: how does one replace that line of code and replace it
with a table valued parameter in such a way that the concatenation
would still work?
Suppose your LocationIdArray has this definition:
create type LocationIdArray as table (LocationId int);
Then your IN should look like this:
and s.Location_ID in (select LocationId from #LocationIDs)
This won't work within your exec because #LocationID is in the outer scope respect to exec, you can pass it as a parameter in sp_executesql but the best you can do is to rewrite your dynamic query to static one as there is no reason to use dynamic code here.

I want to pass a valuelist to my SQL Server stored procedure

I need to pass a list to my SQL Server stored procedure. I have generated the list and it is a comma delimited list of numbers using:
<cfquery name="House" datasource="#application.datasource#">
SELECT cGLsubaccount
FROM HOUSE
WHERE Right(cGLsubaccount,3) IN
(
<cfloop index="i" list="#consulsub#">
<cfoutput>#right(Trim(i) , 3)#,</cfoutput>
</cfloop>
00000000
)
</cfquery>
<cfset GLsubacct = Valuelist(House.cGLsubaccount,",")>
Now, I pass it into the stored procedure using cfprocparam with cfsqltype to varchar(1000). (I read on google that this is the way to pass a list to the stored procedure).
<cfprocparam type="IN" value="#GLsubacct#" DBVARNAME="#GLsubacct" cfsqltype="cf_sql_varchar">
In the stored procedure, I did this:
ALTER PROCEDURE [rw].[sp_EFT_NoticeXLS2] (
#Scope varchar(50)
, #AcctPeriod char(6)
, #CompanyID nchar(10)
, #GLsubacct varchar(1000) = NULL
)
AS......
and the SQL statement in the stored procedure looks like this:
CREATE TABLE #Houses (
iHouse_ID int,
cName varchar(50),
cNumber varchar(10),
cPhoneNumber1 varchar(25),
cAddressLine1 varchar(50),
cCity varchar(30),
cStateCode varchar(2),
cZipCode varchar(10),
iUnitsAvailable int,
iRegOpsNumber int,
cOpsName varchar(50),
iRegionID int,
cRegionName varchar(50)
)
INSERT INTO #Houses (
iHouse_ID,
cName,
cNumber,
cPhoneNumber1,
cAddressLine1,
cCity,
CStateCode,
cZipCode,
iUnitsAvailable,
iRegOpsNumber,
cOpsName,
iRegionID,
cRegionName )
SELECT
h2.iHouse_ID,
h.cName,
h.cNumber,
h.cPhoneNumber1,
h.cAddressLine1,
h.cCity,
h.CStateCode,
h.cZipCode,
h.iUnitsAvailable,
r.RegOpsNumber,
r.opsname,
r.iRegion_ID,
r.regionname
FROM rw.fn_GetScopeHouses (#Scope, #dtReport, NULL, NULL, 0) h2
JOIN House h on h.iHouse_ID = h2.iHouse_ID
AND h.cCompanyID = #CompanyID
AND ( #GLsubacct IS NULL OR h.iHouse_ID IN ('+ #GLsubacct +') )
JOIN rw.vw_Reg_Ops r on r.opsareaID = h.iOpsArea_ID
The problem is that I'm getting an error. The error message is...
Error Executing Database Query.
[Macromedia][SQLServer JDBC Driver][SQLServer]Conversion failed when converting the varchar value '+ #GLsubacct +' to data type int.
The error occurred in E:\inetpub\wwwroot\intranet\TIPS4\Admin\EFTprocesspullfile.cfm: line 46
44 : <cfprocparam type="IN" value="#CompanyID#" DBVARNAME="#CompanyID" cfsqltype="cf_sql_varchar"><!--- TPecku added variable to be passed to the stored Proc --->
45 : <cfif CompanyID EQ 0000>
46 : <cfprocparam type="IN" value="#GLsubacct#" DBVARNAME="#GLsubacct" cfsqltype="cf_sql_varchar">
47 : </cfif>
48 : </cfstoredproc>
The error is in the stored procedure because that is where I have '+ #GLsubacct +'.
Any ideas on what I'm doing wrong? (Sorry for the long post, I wanted to put as much detail as possible so you can understand what I'm doing.
In order to make this work with something close to your existing code, you'll have to create a query string (replacing your insert statement) in the stored procedure and execute it.
I've created some dummy/test variables to see how the query looks using the PRINT statement. You can start with the line of code with "DECLARE #execQuery varchar(MAX)" to the end to replace your insert statement.
Logic like this should fill the temp table #Houses with the data that you can then use.
-- test variables
DECLARE #Scope varchar(50), #AcctPeriod char(6), #CompanyID nchar(10), #GLsubacct varchar(1000), #dtReport VARCHAR(20);
SET #Scope = 'scope';
SET #AcctPeriod = 'fall';
SET #CompanyID = N'coID';
SET #dtReport = 'dtRpt'
SET #GLsubacct = '123,234,345,456'
-- copy code below this line
DECLARE #execQuery varchar(MAX)
SET #execQuery = 'insert into #Houses (
iHouse_ID,
cName,
cNumber,
cPhoneNumber1,
cAddressLine1,
cCity,
CStateCode,
cZipCode,
iUnitsAvailable,
iRegOpsNumber,
cOpsName,
iRegionID,
cRegionName
)
select
h2.iHouse_ID,
h.cName,
h.cNumber,
h.cPhoneNumber1,
h.cAddressLine1,
h.cCity,
h.CStateCode,
h.cZipCode,
h.iUnitsAvailable,
r.RegOpsNumber,
r.opsname,
r.iRegion_ID,
r.regionname
FROM rw.fn_GetScopeHouses ('''+ #Scope +''', '''+ #dtReport +''', NULL, NULL, 0) h2
JOIN House h on h.iHouse_ID = h2.iHouse_ID
AND h.cCompanyID = N'''+ #CompanyID +''''
IF (#GLsubacct IS NOT NULL)
BEGIN
SET #execQuery = #execQuery + ' AND ( h.iHouse_ID IN ('+ #GLsubacct +') )'
END
SET #execQuery = #execQuery + 'JOIN rw.vw_Reg_Ops r on r.opsareaID = h.iOpsArea_ID'
--PRINT #execQuery
EXEC #execQuery
I finally figured out how to make it work. After I passed the list to the stored procedure variable, I couldn't use the variable directly in my sql statement, it didn't work, so what I did was to iterate through the contents of the variable and store them in a temp table. I then used the content of the temp table in my SQL statement. If you look above, you will see what I was trying to do that didn't work. What I ended up doing was....
declare #oneNumber int
declare #POS int
if #GLsubacct <> ''
begin
--Step through the comma delimted list of numbers and plug each one into a temp table
create table #HouseList (HouseID int)
select #POS = patindex('%,%',#GLsubacct)
while #POS > 0
begin
select #oneNumber = cast(left(#GLsubacct,#POS - 1) as int)
insert into #HouseList (HouseID) values (#oneNumber)
select #GLsubacct = right(#GLsubacct,len(#GLsubacct) - #POS)
select #POS = patindex('%,%',#GLsubacct)
end
--do the last one which doesn't have any comma
select #oneNumber = cast(#GLsubacct as int)
insert into #HouseList (HouseID) values (#oneNumber)
end
-- Create #House table
CREATE TABLE #Houses (
iHouse_ID int,
cName varchar(50),
cNumber varchar(10),
cPhoneNumber1 varchar(25),
cAddressLine1 varchar(50),
cCity varchar(30),
cStateCode varchar(2),
cZipCode varchar(10),
iUnitsAvailable int,
iRegOpsNumber int,
cOpsName varchar(50),
iRegionID int,
cRegionName varchar(50))
insert into #Houses (
iHouse_ID,
cName,
cNumber,
cPhoneNumber1,
cAddressLine1,
cCity,
CStateCode,
cZipCode,
iUnitsAvailable,
iRegOpsNumber,
cOpsName,
iRegionID,
cRegionName)
select
h2.iHouse_ID,
h.cName,
h.cNumber,
h.cPhoneNumber1,
h.cAddressLine1,
h.cCity,
h.CStateCode,
h.cZipCode,
h.iUnitsAvailable,
r.RegOpsNumber,
r.opsname,
r.iRegion_ID,
r.regionname
from rw.fn_GetScopeHouses (#Scope, #dtReport, NULL, NULL, 0) h2
JOIN House h on h.iHouse_ID = h2.iHouse_ID
AND h.cGLsubaccount IN (select Houseid from #HouseList)
JOIN rw.vw_Reg_Ops r on r.opsareaID = h.iOpsArea_ID
It worked perfectly!

Showing 'error converting data type nvarchar to bigint. in sql server'

By using nvarchar(Max) and join the query and execute by EXEC sp_executesql during this process it showing the above error error converting data type nvarchar to bigint. in sql server, with out using the joining and sp_executesql it will workd perfect. how can i solve the this error in sql.
DECLARE
#mainSqlQuery nvarchar(max),
#GroupBySection nvarchar(max)
-- Insert statements for procedure here
SELECT #mainSqlQuery = N'--
SELECT
BRCH.BranchName [BranchName],
ASI.SubInventoryName [SubInventory],
APRO.ProductName [Product],
ASICT.TransactDateTime [DateTime],
ASICT.ProductStock [Stock],
ASICT.ProductStockInLocalCrrncy [Local Stock] INTO #MyTempTable
FROM ALX_SubInventoryCashTransfers ASICT
INNER JOIN
ALX_Branches BRCH ON BRCH.BranchID= ASICT.BranchID
INNER JOIN
ALX_SubInventories ASI ON ASI.SubInventoryID=ASICT.SubInventoryID
INNER JOIN
ALX_Products APRO ON APRO.ProductID= ASICT.ProductID
INNER JOIN
(SELECT
BranchID,
SubInventoryID,
ProductID,
MAX(TransactDateTime) AS MaxDate
FROM ALX_SubInventoryCashTransfers'
Select #GroupBySection = N'-- GROUP BY BranchID,
SubInventoryID,
ProductID) SubASICT
ON ASICT.BranchID = SubASICT.BranchID
AND ASICT.SubInventoryID = SubASICT.SubInventoryID
AND ASICT.ProductID = SubASICT.ProductID
AND ASICT.TransactDateTime = SubASICT.MaxDate'
Declare #Condition nvarchar(max)
if(#Date is null)
BEGIN
Select #Condition='WHERE
(( ISNULL(ProductID,0)=''' +#ProductID+') OR'+#ProductID+'''=0)AND
(( ISNULL(BranchID,0)=''' +#BranchID+') OR '+#BranchID+'''=0) '
Declare #Query nvarchar(max);Select #Query=#mainSqlQuery+#Condition+#GroupBySect
EXEC sp_executesql #Query;
END
IF(#Date is not null)
BEGIN
Select #Condition='WHERE
CONVERT(DATETIME,FCSB.FCBuySellDate,105)=''' +#Date+''' AND
(( ISNULL(ProductID,0)=''' +#ProductID+') OR'+#ProductID+'''=0)AND
(( ISNULL(BranchID,0)=''' +#BranchID+') OR '+#BranchID+'''=0) '
Declare #Query1 nvarchar(max);Select #Query=#mainSqlQuery+#Condition+#GroupBySection;
EXEC sp_executesql #Query1;
END
*NOTE :-in this i need a condition to work in the where clause ,( Date is the main problem if date is null i need to display all details but in this when i put null in date no data will come, so i prefer this method but i know it is a worst method but the date condition need to display like this any other opinion to overcome the date in the where clause
What type are #ProductID, #BranchID and #Date? I would try to convert those values to varchar explicitly when creating the condition.

Resources