Invalid Column Name - Column Does Exist - sql-server

I have a table to which I added a new column, as such:
ALTER TABLE [Invoice].[Invoice] ADD [DaysToPay] int
GO
ALTER TABLE [Invoice].[Invoice] ADD CONSTRAINT [DF_Invoice_DaysToPay] DEFAULT ((30)) FOR [DaysToPay]
GO
UPDATE [Invoice].[Invoice] SET [DaysToPay] = 30
GO
ALTER TABLE [Invoice].[Invoice] ALTER COLUMN [DaysToPay] int NOT NULL
GO
If I now do SELECT * FROM [Invoice].[Invoice] I get an Invalid column name 'DaysToPay' error. I get this error whether I run the statement through SSMS or any other means (via code).
The same error occurs with or without the column when I select specific columns. e.g. SELECT [InvoiceID] FROM [Invoice].[Invoice].
I have closed SSMS and restarted the SQL service. Still the same error.
The column was added under the same user that is getting the error and that same user is the owner of the schema.
Both these statements return 0 rows:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'DaysToPay'
SELECT *
FROM sys.columns
WHERE Name = N'DaysToPay'
I've tried Ctrl + Shift + R but I don't think it's a SSMS thing and it made no difference.
The database is not replicated.
I ran a DBCC OPENTRAN are there were none active.
I have since removed the column (manually using the designer in SSMS) and I still get the same error. The table shows correctly in the SSMS designer (as it did prior to me manually removing it).
Any ideas other than dropping and re-creating the table?
EDIT:
The rest of the script that was run is as follows (I have removed certain columns so as not to identify):
ALTER PROCEDURE [Invoice].[Invoice_Save] (
#InvoiceID int,
#TypeID int,
#InvoiceNumber int,
#InvoiceDate datetime,
#DatePaid datetime,
#PaymentEnteredBy int,
#AmountPaid float,
#PaymentTypeID int,
#HasVAT bit,
#VATRate float,
#TranslationPercentageCharge float,
#IsVoid bit,
#VoidDate datetime,
#VoidBy int,
#DateSent datetime,
#SentBy int,
#PurchaseOrderNumber varchar(100),
#BillingContact varchar(255),
#BillingAddress varchar(MAX),
#BillingContactEmail nvarchar(255),
#BillingContactTelNo varchar(50),
#Notes varchar(MAX),
#CompanyID int,
#DaysToPay int,
#DateCreated datetime,
#CreatedBy int,
#LastUpdated datetime,
#LastUpdatedBy int
)
AS
IF NOT EXISTS (SELECT * FROM [Invoice].[Invoice] WHERE [InvoiceID] = #InvoiceID)
BEGIN
INSERT INTO [Invoice].[Invoice] ([TypeID], [InvoiceNumber], [InvoiceDate], , [DatePaid], [PaymentEnteredBy], [AmountPaid], [PaymentTypeID], [HasVAT], [VATRate], [TranslationPercentageCharge], [IsVoid], [VoidDate], [VoidBy], [DateSent], [SentBy], [PurchaseOrderNumber], [BillingContact], [BillingAddress], [BillingContactEmail], [BillingContactTelNo], [Notes], [CompanyID], [DaysToPay], [DateCreated], [CreatedBy], [LastUpdated], [LastUpdatedBy])
VALUES (#TypeID, #InvoiceNumber, #InvoiceDate, #DatePaid, #PaymentEnteredBy, #AmountPaid, #PaymentTypeID, #HasVAT, #VATRate, #TranslationPercentageCharge, #IsVoid, #VoidDate, #VoidBy, #DateSent, #SentBy, #PurchaseOrderNumber, #BillingContact, #BillingAddress, #BillingContactEmail, #BillingContactTelNo, #Notes, #CompanyID, #DaysToPay, #DateCreated, #CreatedBy, #LastUpdated, #LastUpdatedBy)
SELECT MAX([InvoiceID]) AS MaxID FROM [Invoice].[Invoice]
END
ELSE
UPDATE [Invoice].[Invoice]
SET [TypeID] = #TypeID,
[InvoiceNumber] = #InvoiceNumber,
[InvoiceDate] = #InvoiceDate,
[DatePaid] = #DatePaid,
[PaymentEnteredBy] = #PaymentEnteredBy,
[AmountPaid] = #AmountPaid,
[PaymentTypeID] = #PaymentTypeID,
[HasVAT] = #HasVAT,
[VATRate] = #VATRate,
[TranslationPercentageCharge] = #TranslationPercentageCharge,
[IsVoid] = #IsVoid,
[VoidDate] = #VoidDate,
[VoidBy] = #VoidBy,
[DateSent] = #DateSent,
[SentBy] = #SentBy,
[PurchaseOrderNumber] = #PurchaseOrderNumber,
[BillingContact] = #BillingContact,
[BillingAddress] = #BillingAddress,
[BillingContactEmail] = #BillingContactEmail,
[BillingContactTelNo] = #BillingContactTelNo,
[Notes] = #Notes,
[CompanyID] = #CompanyID,
[DaysToPay] = #DaysToPay,
[DateCreated] = #DateCreated,
[CreatedBy] = #CreatedBy,
[LastUpdated] = #LastUpdated,
[LastUpdatedBy] = #LastUpdatedBy
WHERE [InvoiceID] = #InvoiceID
GO

Related

Passing multiple values to parameters from an existing table

I am trying to create a stored procedure which passes values from select statement of joined tables as parameters to another stored procedure inside to create return credit for returned purchase which are assigned in the WHERE clause of joined tables (#RANO and #returndate). I want to pass many customers (as #Customer) from the joined tables to the stored procedure CreateManCreditHDFromReturn but it picks the first #RANO in the WHERE clause of the joined statement!
How can I pass multiple values (like customers, divisions,...) from all RANOs in the where clause of the joined table?
Note: RANO mean return authorization of returned purchase.
ALTER PROCEDURE [dbo].[CreateEllieAutoCreditHDFromReturn]
AS
BEGIN
DECLARE #ARReason nVarChar(5),
#DocumentDate Datetime,
#ARDocumentType VarChar(5),
#TRANSACTIONID INT,
#TIMELASTMOD DATETIME,
#USERIDLASTMOD nvarchar(5),
#CompanyCode nVarChar(10),
#Customer nVarChar(10),
#Division nVarChar(5),
#Warehouse nVarChar(10),
#Salesman1 nVarChar(10),
#Currency nVarChar(3),
#ReturnNo int,
#RANO int,
#Style nvarchar(15),
SELECT #Pkey = #CompanyCode = rh.companycode,
#Customer = rh.CUSTOMER,
#Division = rh.DIVISION,
#Warehouse = rh.WAREHOUSE,
#Salesman1 = rh.SALESMAN1,
#Currency = rh.CURRENCY,
#ReturnNo = rh.returnno,
#RANO = rh.RANO
FROM
ReturnDetail rd
INNER JOIN
ReturnHeader rh ON rh.RETURNNO = rd.RETURNNO
WHERE
rh.RETURNDATE >= '2020-03-27 00:00:00'
AND rh.RETURNDATE < '2020-03-28 00:00:00'
AND rd.RANO IN (79383, 79820)
AND rd.ARDOCUMENTNOCOMPANY = 0
SET #ARReason = 'RM'
SET #ARDocumentType = 'RCRDT'
SET #DocumentDate = GETDATE()
SET #TRANSACTIONID = 0
SET #TIMELASTMOD = GETDATE()
SET #USERIDLASTMOD = 'WSchan'
SET #ReferenceNo = 0
DECLARE #CurrDocumentNo Int,#CurrDocumentNoCompany Int
EXEC dbo.CreateManCreditHDFromReturn
#CompanyCode,
#ARReason,
#Customer,
#Division,
#Warehouse,
#Salesman1,
#Currency,
#DocumentDate,
#ReferenceNo,
#ARDocumentType,
#CurrDocumentNo OUTPUT,
#CurrDocumentNoCompany OUTPUT,
#TRANSACTIONID,
#TIMELASTMOD,
#USERIDLASTMOD
END
You can't assign multiple values to scalar variables. If you are restricted in that you have no access to modify dbo.CreateManCreditHDFromReturn then you have to use a cursor or loop and iterate through each record in your query. The stored procedure is coded to accept one value at a time for its input parameters.
If you have the ability to modify dbo.CreateManCreditHDFromReturn then you can update it to accept a table variable, JSON, or XML and then inside that stored procedure you can unpack the input and process it accordingly.
If you have to use a cursor, which I'm guessing is going to be the case, it would look something like this:
DECLARE #CompanyCode NVARCHAR(10);
[...and other variables...]
DECLARE RANOCURS CURSOR FOR
SELECT CompanyCode, [...and other fields...]
FROM ReturnDetail rd
INNER JOIN ReturnHeader rh ON rh.RETURNNO = rd.RETURNNO
WHERE rh.RETURNDATE >= '2020-03-27 00:00:00'
AND rh.RETURNDATE< '2020-03-28 00:00:00'
AND rd.RANO IN (79383, 79820)
AND rd.ARDOCUMENTNOCOMPANY = 0;
OPEN RANOCURS;
FETCH NEXT FROM RANOCURS INTO #CompanyCode, [...other variables...]
DECLARE #CurrDocumentNo INT, #CurrDocumentNoCompany INT;
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC dbo.CreateManCreditHDFromReturn
#CompanyCode ,
[...other variable parameters...],
#CurrDocumentNo OUTPUT,
#CurrDocumentNoCompany OUTPUT;
[...do something with the return values...]
FETCH NEXT FROM RANOCURS INTO #CompanyCode, ...[other fields]
END;
CLOSE RANOCURS;
DEALLOCATE RANOCURS;

How to convert a query to a a function

I'm playing around with a query from a software partner that i did not create. I'm trying to use it as a function that i can insert into a table, since i'm no sql expert i'm having difficulties with the sintax.
Thanks to your suggestions i'm making progress, now i'm stuck on how to add an additional select to include some join tables, i have disabled that part converting it to a comment. This actually works without the final select but i need the final select, any ideas?
alter function Renetest
(
#companytest nvarchar(8),
#fiscalyeartest int
)
returns #PERIODBALANCE TABLE
(
[Company] NVARCHAR(8)
,[BookID] NVARCHAR(12)
,[BalanceAcct] NVARCHAR(200)
,[FiscalYear] INT
,[FiscalPeriod] INT
,[BalanceType] NVARCHAR(1)
,[SegValue1] NVARCHAR(50)
,[SegValue2] NVARCHAR(50)
,[FiscalYearSuffix] NVARCHAR(8)
,[FiscalCalendarID] NVARCHAR(12)
)
as
begin
Declare #company nvarchar(8);
Declare #fiscalyear INT;
DECLARE #FiscalPeriod INT;
Set #company = 'epic03'
set #Fiscalyear = '2013'
SET #FiscalPeriod=0;
DECLARE #MaxPeriod AS NVARCHAR(20);
SET #MaxPeriod=(
SELECT
MAX([Erp].[GLBookPer].[FiscalPeriod])
FROM
[Erp].[GLBookPer] WITH (NOLOCK)
WHERE
[Erp].[GLBookPer].[Company] IN (#company)
AND [Erp].[GLBookPer].[FiscalYear]=#FiscalYear
);
WHILE #FiscalPeriod<=(#MaxPeriod)
BEGIN
INSERT INTO #PERIODBALANCE
(
[Company]
,[BookID]
,[BalanceAcct]
,[FiscalYear]
,[FiscalPeriod]
,[BalanceType]
,[SegValue1]
,[SegValue2]
,[FiscalYearSuffix]
,[FiscalCalendarID]
)
SELECT
[Erp].[GLPeriodBal].[Company]
,[Erp].[GLPeriodBal].[BookID]
,[Erp].[GLPeriodBal].[BalanceAcct]
,[Erp].[GLPeriodBal].[FiscalYear]
,#FiscalPeriod AS [FiscalPeriod]
,[Erp].[GLPeriodBal].[BalanceType]
,[Erp].[GLPeriodBal].[SegValue1]
,[Erp].[GLPeriodBal].[SegValue2]
,[Erp].[GLPeriodBal].[FiscalYearSuffix]
,[Erp].[GLPeriodBal].[FiscalCalendarID]
FROM
[Erp].[GLPeriodBal] WITH (NOLOCK)
WHERE
[Erp].[GLPeriodBal].[Company] IN (#company)
AND [Erp].[GLPeriodBal].[FiscalYear]=#FiscalYear
AND [Erp].[GLPeriodBal].[FiscalPeriod]<=#FiscalPeriod
AND [Erp].[GLPeriodBal].[BalanceType] IN ('D','B')
SET #FiscalPeriod=#FiscalPeriod+1;
end;
/*
SELECT
LTRIM(RTRIM([PERIODBALANCE].[Company])) AS [Company]
,LTRIM(RTRIM([PERIODBALANCE].[BookID])) AS [BookID]
,LTRIM(RTRIM(REPLACE([PERIODBALANCE].[BalanceAcct],'|','-'))) AS [BalanceAcct]
,LTRIM(RTRIM(ISNULL(NULLIF([PERIODBALANCE].[BalanceType],''),'--'))) AS [BalanceType]
,LTRIM(RTRIM(ISNULL(NULLIF([PERIODBALANCE].[FiscalYearSuffix],''),'--'))) AS [FiscalYearSuffix]
,LTRIM(RTRIM(ISNULL(NULLIF([PERIODBALANCE].[FiscalCalendarID],''),'--'))) AS [FiscalCalendarID]
FROM
#PERIODBALANCE AS [PERIODBALANCE]*/
return
end
go
The function returns a table. Just select from the function with an INSERT statement.
INSERT INTO dbo.MyTable
SELECT Company, BookID
FROM Renetest();
This is strictly what you asked. But this could be converted into a stored procedure and avoid using a function all together.

Calling a stored procedure in a command object in crystal reports 11 with a date parameter

I have a stored procedure that is in a command object inside a Crystal Report. I need to pass it a date. I defined startdate and enddate in the command parameter window.
This is how I defined the object parameters in Crystal:
Startdate – string . default value = ‘t-1’
Enddate - string. default value = ‘t-1’
It does not error out but runs forever and I have to terminate it. What am I doing wrong?
This is the code inside the command object in Crystal:
DECLARE #StatisticStartDate as datetime = EPIC_UTIL.EFN_DIN({?startdate});
DECLARE #StatisticEndDate as datetime = dateadd(s, 86399, EPIC_UTIL.EFN_DIN({?enddate}));
DECLARE
--#StatisticStartDate nvarchar(20), -- Change all of these to the data types of the specific columns...
--#StatisticEndDate nvarchar(20),
#CostCenterList nvarchar(200),
#ProcedureCodeList nvarchar(100),
#Statistic nvarchar(100),
#StatisticDescription VARCHAR(255),
#RVValue numeric(18,0),
#Fiscalyear int,
#PatientTypeIndicator nvarchar(100),
#PatientServiceList nvarchar(100),
#PatientClassList nvarchar(100),
#PatientStatusList nvarchar(100);
DECLARE #Output TABLE (
[Facility ID] INT,
[Stat Date] DATETIME,
[DEPARTMENT] VARCHAR(200),
[Statistic Name] VARCHAR (200),
[Statistic Description] VARCHAR (200) ,
[Patient Type Indicator] VARCHAR (2),
[Daily Quantity] DECIMAL(18,2) ,
[Daily Amount] DECIMAL(18,2),
COST_CENTER_NAME VARCHAR(200) ,
[Fiscal Year] INT
)
DECLARE Setting_cur CURSOR FOR
SELECT
StatisticStartDate,
StatisticEndDate,
CostCenterList,
ProcedureCodeList,
Statistic,
StatisticDescription,
PatientTypeIndicator,
RVThreshold,
PatientServiceList,
PatientClassList,
PatientStatusList,
FiscalYear
FROM
ssisconfiguration.dbo.BalladHealthDayOneStats
--WHERE
--FiscalYear = 2017
;
OPEN Setting_cur
FETCH NEXT FROM Setting_cur INTO #StatisticStartDate, #StatisticEndDate,
#CostCenterList, #ProcedureCodeList,
#Statistic, #StatisticDescription,
#PatientTypeIndicator, #RVValue,
#PatientServiceList, #PatientClassList,
#PatientStatusList, #FiscalYear
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT #Output
EXEC [SSIS].[sp_BalladDayOneMaster] --#RCout = Clarity.ssis.sp_GetFinancialStatsByFinParams
#SD = #StatisticStartDate,
#ED = #StatisticEndDate,
#CostCenterList = #CostCenterList,
#ProcedureCodeList = #ProcedureCodeList,
#Statname = #Statistic,
#StatDescription = #StatisticDescription,
#PatientTypeIndicator = #PatientTypeIndicator,
#RVvalue = #RVValue,
#FiscalYear = #FiscalYear,
#PatientClassList = #PatientClassList ,
#PatientStatusList = #PatientStatusList,
#PatientServiceList = #PatientServiceList
FETCH NEXT FROM Setting_cur INTO #StatisticStartDate, #StatisticEndDate,
#CostCenterList, #ProcedureCodeList,
#Statistic, #StatisticDescription,
#PatientTypeIndicator, #RVValue,
#PatientServiceList, #PatientClassList,
#PatientStatusList, #FiscalYear
END
CLOSE Setting_cur
DEALLOCATE Setting_cur
SELECT * FROM #Output
Instead of insert all the code inside the command object I would suggest you to create the stored procedure and select that one when you create the new report, so you can debug the stored procedure from sql server.

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!

how to write update procedure with scope identity

My insert procedure is working fine the way i want. But update is not working with scope identity.
SET ANSI_NULLS ON
ALTER PROCEDURE [dbo].[spr_unitCreation]
(
#Unit_Name VARCHAR(50) = NULL,
#Unit_Abbreviation VARCHAR(50) = NULL,
#Unit_type VARCHAR(50) = NULL,
#Decimal_Places VARCHAR(50) = NULL,
#Description VARCHAR(50) = NULL,
#Super_Unit VARCHAR(50) = NULL,
#Per_Unit VARCHAR(50) = NULL,
#unit_Id INT OUTPUT,
#abc VARCHAR(50) = NULL
)
AS
BEGIN
IF #abc = 'update' BEGIN
SET NOCOUNT ON;
SELECT #unit_Id AS SCOPE_IDENTITY
UPDATE tbl_UnitCreation
SET Unit_Name = #Unit_Name,
Unit_Abbreviation = #Unit_Abbreviation,
Unit_type = #Unit_type,
Decimal_Places = #Decimal_Places,
Description = #Description,
Super_Unit = #Super_Unit,
Per_Unit = #Per_Unit
WHERE unit_Id = #unit_Id
END
END
SELECT * FROM tbl_UnitCreation
SCOPE_IDENTITY returns the last identity value inserted into an identity column. You are not inserting a row.
To update a row all you need is to pass a value to #unit_Id when executing [spr_unitCreation]. Also remove the line "SELECT #unit_Id AS SCOPE_IDENTITY" from your code.
Based on the comments, you need to find the correct id by searching on relevant details. So you can get the id like this:
SELECT #unit_Id = unit_Id
FROM tbl_UnitCreation
WHERE Unit_Name=#Unit_Name -- NB: Ensure this column contains your relevant details
Another commonly used option is to use the OUTPUT clause of the UPDATE statement, inserting all the updated/"inserted" primary keys and Unit_name into a tablevariable.
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-2017

Resources