SQL Server can't get current incremented row from table variable - sql-server

I am running into a problem getting my recursive script to find the current row from a table variable. I have verified that there is data in the table variable. That part is working great, however the next part of my script keeps hitting my else statement. It worked great with temp tables but I am trying to get this into a function so I can call it easier with other scripts.
BEGIN
DECLARE #totalrows INT
DECLARE #currentrow INT = 1
DECLARE #tempTable TABLE (value VARCHAR(255), ID INT)
SELECT * Into #temp FROM dbo.fn_split((SELECT TOP (1) address_full FROM sde.gis.BUSINESS), ' ')
ALTER TABLE #temp
ADD ID INT IDENTITY
INSERT into #tempTable ( value, ID )
SELECT *
FROM #temp
SELECT * FROM #tempTable
DECLARE #address_no MONEY
DECLARE #pre_dir VARCHAR(2)
DECLARE #street_name VARCHAR(45)
DECLARE #suffix VARCHAR(20)
WHILE ( #currentrow <= #totalrows )
BEGIN
DECLARE #cur_value VARCHAR(50)
SELECT #cur_value = value
FROM #tempTable
WHERE id = #currentrow
PRINT 'Working on ' + #cur_value
IF ( #currentrow = 1 )
BEGIN
IF ( ISNUMERIC(#cur_value) = 1 )
SET #address_no = CAST(#cur_value AS MONEY)
ELSE
RETURN
END
IF ( #currentrow = 2 ) -- Is this a direciton
BEGIN
IF EXISTS ( SELECT 1
FROM mead.dbo.street_direction
WHERE street_direction = #cur_value )
BEGIN
SET #pre_dir = #cur_value
END
ELSE
BEGIN
SET #street_name = #cur_value
END
END
IF ( #currentrow > 2 ) -- Is this a direciton
BEGIN
IF EXISTS ( SELECT 1
FROM mead.dbo.street_type
WHERE street_type = #cur_value )
BEGIN
SET #suffix = #cur_value
END
ELSE
BEGIN
IF ( #street_name IS NULL )
SET #street_name = #cur_value
ELSE
SET #street_name = #street_name + ' ' + #cur_value
END
END
SET #currentrow = #currentrow + 1
END
END
SELECT #address_no ,
#pre_dir ,
#street_name ,
#suffix
DROP TABLE #temp

Answered my own question. Forgot to set my totalrows = ##rowcount.

Related

Return first five numbers form string within UDF

I am working on SQL Server (2005,2008 & 2012)
I wanna extract first five numbers from varchar column via using UDF
Input:
rrr123ddd4567ddd19828www2
123hhhsss124ss18762s
qq12349wsss12376ss
Output:
19828
18762
12349
My Trail is as following:
DECLARE
#myString VARCHAR(1000),
#temp VARCHAR(100),
#position INT,
#ExecuteInsert nvarchar (500),
#FirstChar bit
SET #myString = 'rrr123ddd4567ddd19828www2'
SET #position = 1
SET #FirstChar = 1
WHILE #position <= LEN(#myString)
BEGIN
IF (ISNUMERIC(SUBSTRING(#myString,#position,1))) = 1
BEGIN
SET #temp = isnull(#temp,'') + SUBSTRING(#myString,#position,1)
SET #FirstChar = 1
END
ELSE /* The char is alphabetical */
BEGIN
if (#FirstChar= 1)
BEGIN
SET #temp = isnull(#temp,'') + ','
SET #FirstChar = 0
END
END
SET #position = #position + 1
END
IF (RIGHT(#temp,1) <> ',')
BEGIN
SET #temp = #temp + ','
END
SELECT #temp = REPLACE(','+ #temp + ',',',,','')
SELECT #temp = Replace (#temp,',','''),(''')
Select #temp = '(''' + #temp + ''')'
Create table #temp
(
col1 varchar(100)
)
SET #ExecuteInsert = 'insert into #temp values ' + #temp
Execute sp_executesql #ExecuteInsert
select top 1 col1 from #temp
where LEN(col1) = 5
drop table #temp
-- Output >> 19828
The previous query is working well with string input , but I wanna using this code within UDF to could using it with columns.
if I used the previous query within UDF, the following error is raising:
Cannot access temporary tables from within a function.
EDIT
if I used Table variable , I get the next error:
Only functions and some extended stored procedures can be executed
from within a function.
any help will be greatly appreciated.
CREATE FUNCTION udfTest
(
-- Add the parameters for the function here
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE
#Result int,
#myString VARCHAR(1000),
#temp VARCHAR(100),
#position INT,
#ExecuteInsert nvarchar (500),
#FirstChar bit
SET #myString = 'rrr123ddd4567ddd19828www2'
SET #position = 1
SET #FirstChar = 1
WHILE #position <= LEN(#myString)
BEGIN
IF (ISNUMERIC(SUBSTRING(#myString,#position,1))) = 1
BEGIN
SET #temp = isnull(#temp,'') + SUBSTRING(#myString,#position,1)
SET #FirstChar = 1
END
ELSE /* The char is alphabetical */
BEGIN
if (#FirstChar= 1)
BEGIN
SET #temp = isnull(#temp,'') + ','
SET #FirstChar = 0
END
END
SET #position = #position + 1
END
IF (RIGHT(#temp,1) <> ',')
BEGIN
SET #temp = #temp + ','
END
SELECT #temp = REPLACE(','+ #temp + ',',',,','')
SELECT #temp = Replace (#temp,',','''),(''')
Select #temp = '(''' + #temp + ''')'
Declare #tempTable TABLE
(
col1 varchar(100)
)
insert into #tempTable SELECT #temp
select top 1 #Result=col1 from #tempTable
where LEN(col1) = 5
return #Result
END
GO
Here you are my answer of my question , hope helps others.
The objective is creating UDF function for using it with columns, not only fixed values.
The approach is using SplitString instead of sp_executesql
for splitting a comma separated string and loop it's values in table.
Demo:-
Create table DummyTable
( col1 varchar (100))
go
Insert into DummyTable values ('rrr123ddd4567ddd19828www2')
Insert into DummyTable values ('123hhhsss124ss18762s')
Insert into DummyTable values ('qq12349wsss12376ss')
go
/*
SplitString via Mudassar Khan
http://www.aspsnippets.com/Articles/Split-and-convert-Comma-Separated-Delimited-String-to-Table-in-SQL-Server.aspx
*/
Create FUNCTION SplitString
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
GO
-------------------------------------
-------------------------------------
-------------------------------------
/*
My Own Function
*/
Create FUNCTION udfGetFirstFiveNumbers
(
#myString VARCHAR(1000)
)
RETURNS varchar(100)
AS
BEGIN
DECLARE
#temp VARCHAR(100),
#result Varchar (100),
#position INT,
#ExecuteInsert nvarchar (500),
#FirstChar bit
SET #position = 1
SET #FirstChar = 1
WHILE #position <= LEN(#myString)
BEGIN
IF (ISNUMERIC(SUBSTRING(#myString,#position,1))) = 1
BEGIN
SET #temp = isnull(#temp,'') + SUBSTRING(#myString,#position,1)
SET #FirstChar = 1
END
ELSE /* The char is alphabetical */
BEGIN
if (#FirstChar= 1)
BEGIN
SET #temp = isnull(#temp,'') + ','
SET #FirstChar = 0
END
END
SET #position = #position + 1
END
IF (RIGHT(#temp,1) <> ',')
BEGIN
SET #temp = #temp + ','
END
SELECT #temp = REPLACE(','+ #temp + ',',',,','')
SELECT #result = Item
FROM dbo.SplitString(#temp, ',')
where len(Item) = 5
return #result
END
GO
-- Test
select col1, dbo.udfGetFirstFiveNumbers(col1) as result
from DummyTable
Result:-

SQL Server : function not working in trigger

I have trigger on insert like that :
ALTER TRIGGER [dbo].[trTblNameSetRefNo]
ON [dbo].[TblName]
AFTER INSERT
AS BEGIN
UPDATE TblName
SET RefNumber = dbo.GetNextRefNo(i.SomeField)
FROM TblName
INNER JOIN inserted i on i.ID = TblName.ID
END
But it doesn't work. When I 'hardcode' field RefNumber , for example : SET RefNumber = 'test', it works correctly.
Also when I call function outside of the trigger, it return proper result.
And this is my function that must return value in trigger :
ALTER FUNCTION [dbo].[GetNextRefNo]
(#ValueField INT)
RETURNS NVARCHAR(250)
AS
BEGIN
DECLARE #lastId INT;
DECLARE #result NVARCHAR(25);
DECLARE #CurrentIdentifier NVARCHAR(25);
SELECT TOP 1
#lastId = CAST(Substring(RefNumber, Charindex('-', RefNumber) + 4, Len(RefNumber )) AS INT) + 1
FROM
TblName
ORDER BY
ID DESC
IF ##ROWCOUNT < 1 --if empty table , set start number
BEGIN
SET #lastId = 1000
END
SELECT #CurrentIdentifier = 'SIT'
SET #result = #CurrentIdentifier + '-' + Substring ( Cast(Year(Getdate()) AS NVARCHAR), 3, 2) + '-' + Cast(#lastId AS NVARCHAR)
RETURN #result
END
Any ideas what I'm doing wrong?
Your function returns what is probably an incorrect result when RefNumber = '' and it returns NULL when RefNumber = NULL, as would happen for a newly inserted record.
The design of the above code is beyond bad.
Suggested approach:
Use ID field as the counter and generate RefNumber based on that, while concatating Year as needed.
Example function:
ALTER FUNCTION [dbo].[GetNextRefNo] (#ID INT)
returns NVARCHAR(250)
AS
BEGIN
DECLARE #lastId INT;
DECLARE #result NVARCHAR(25);
DECLARE #CurrentIdentifier NVARCHAR(25);
SELECT #CurrentIdentifier = 'SIT'
SET #ID = #ID + 1000
SET #result = #CurrentIdentifier + '-' + Substring ( Cast(Year(Getdate()) AS NVARCHAR), 3, 2) + '-' + Cast(#ID AS NVARCHAR)
RETURN #result
END
Example Trigger:
ALTER TRIGGER [dbo].[trTblNameSetRefNo] ON [dbo].[TblName]
AFTER INSERT AS BEGIN
UPDATE TblName
SET RefNumber = dbo.GetNextRefNo(i.ID)
FROM TblName
INNER JOIN inserted i on i.ID = TblName.ID
END
Alternatively create another table to hold the current RefNumber seed.

Invalid column name '#Results'

alter PROCEDURE sp_Get_CustInfoSerach2
(#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
,#ColumnName VARCHAR(50)=null
,#Value VARCHAR(50)=null
,#ddlValue VARCHAR(50)=null
,#txtValue VARCHAR(50)=null
,#status varchar(30))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
if #txtValue IS NULL
Begin
SET #Value = ''''+#ddlValue+ ''''
End
else if #ddlValue IS NULL
begin
SET #Value = ''''+#txtValue+ ''''
end
SET #cmd = 'SELECT ROW_NUMBER() OVER
(
ORDER BY C_Register.UserId desc
)AS RowNumber
,C_Register.UserId, C_Register.Name, C_Register.UserName, C_Register.Status,
Packages.PackagePeriod, Packages.PackageName, C_Register.ActivationDate,
Receive_Payment.OldExpiryDate, Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName, C_Register.Address,C_Register.CreatedDate
INTO'+ #Results+'
FROM C_Register INNER JOIN Receive_Payment ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = '+#status+'And
' + #ColumnName + ' = ' + #Value
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
EXEC(#cmd)
END
throwing error:
Invalid column name '#Results'.
how to solve it?
If i understand your problem correctly you should first exec dynamic sql before select from temporary table
Alter PROCEDURE sp_Get_CustInfoSerach2
(
#PageIndex INT = 1 ,
#PageSize INT = 10 ,
#RecordCount INT OUTPUT ,
#ColumnName VARCHAR(50)=null ,
#Value VARCHAR(50)=null ,
#ddlValue VARCHAR(50)=null ,
#txtValue VARCHAR(50)=null ,
#status varchar(30)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
If #txtValue IS NULL
Begin
SET #Value = ''''+#ddlValue+ ''''
End
Else
if #ddlValue IS NULL
Begin
SET #Value = ''''+#txtValue+ ''''
End
SET #cmd = 'SELECT ROW_NUMBER() OVER ( ORDER BY C_Register.UserId desc )AS RowNumber,
C_Register.UserId, C_Register.Name, C_Register.UserName, C_Register.Status,
Packages.PackagePeriod, Packages.PackageName, C_Register.ActivationDate,
Receive_Payment.OldExpiryDate, Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName, C_Register.Address,C_Register.CreatedDate
INTO #Results
FROM C_Register INNER JOIN Receive_Payment ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = '+#status+'And
' + #ColumnName + ' = ' + #Value
/*First Execute above dynamic Sql query */
EXEC(#cmd)
/* From the above execute statemnet the query will executed and temporary table will created on the fly */
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
Problem in your query is creation of temp table thats not right way to create temp table inside dynamic query.
But even if you create temp table inside a dynamic query it can be accessed only inside the session of dynamic query. If you try to select the temp outside of dynamic query which is created inside the dynamic query you will get a error saying object doesnot exist.
Since you know the number of columns present in the result of dynamic query you can create the temp table outside of dynamic query and insert the records through dynamic query.
Try changing your procedure like this.
ALTER PROCEDURE Sp_get_custinfoserach2 (#PageIndex INT = 1,
#PageSize INT = 10,
#RecordCount INT output,
#ColumnName VARCHAR(50)=NULL,
#Value VARCHAR(50)=NULL,
#ddlValue VARCHAR(50)=NULL,
#txtValue VARCHAR(50)=NULL,
#status VARCHAR(30))
AS
BEGIN
SET nocount ON;
DECLARE #cmd AS NVARCHAR(max)
IF #txtValue IS NULL
BEGIN
SET #Value = '''' + #ddlValue + ''''
END
ELSE IF #ddlValue IS NULL
BEGIN
SET #Value = '''' + #txtValue + ''''
END
/*create a temp as same structure of your dynamic query select statement*/
CREATE TABLE #result
(
rownum INT,
userid INT,
NAME VARCHAR(100),
username VARCHAR(100),
status VARCHAR(15),
packageperiod VARCHAR(15),
packagename VARCHAR(100),
activationdate DATETIME,
oldexpirydate DATETIME,
balance NUMERIC(22, 4),
pyingamount NUMERIC(22, 4),
lastpaiddate DATETIME,
lastupdatetime DATETIME,
areaname VARCHAR(100),
mobno INT,
empname VARCHAR(100),
address VARCHAR(5000),
createddate DATETIME
)
SET #cmd =
' Insert into #result
SELECT ROW_NUMBER() OVER (ORDER BY C_Register.UserId desc )AS RowNumber,
C_Register.UserId, C_Register.Name, C_Register.UserName,
C_Register.Status, Packages.PackagePeriod, Packages.PackageName,
C_Register.ActivationDate,Receive_Payment.OldExpiryDate,
Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName,
C_Register.Address,C_Register.CreatedDate
FROM C_Register
INNER JOIN Receive_Payment
ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area
ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee
ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages
ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = ' + #status + ' And ' + #ColumnName + ' = ' + #Value
SELECT #RecordCount = Count(*)
FROM #results
SELECT *
FROM #results
WHERE rownumber BETWEEN( #PageIndex - 1 ) * #PageSize + 1 AND( (
( #PageIndex - 1 ) * #PageSize + 1 ) +
#PageSize ) - 1
DROP TABLE #results
EXEC(#cmd)
END
Note : I have given generic datatypes to temp table columns please change the datetypes according to your schema.

Why is this function non-deterministic?

Why does SQL Server think this function is non-deterministic?
CREATE FUNCTION [Util].[BuildStreetFullName]
(
#StreetNumber VARCHAR(20),
#StreetDir VARCHAR(2),
#StreetName VARCHAR(50) ,
#StreetType VARCHAR(4) ,
#StreetPostDir VARCHAR(2)
)
RETURNS VarChar(100)
AS
BEGIN
SET #StreetNumber = NULLIF( Util.Trim(#StreetNumber ), '');
SET #StreetDir = NULLIF( Util.Trim(#StreetDir ), '');
SET #StreetName = NULLIF( Util.Trim(#StreetName ), '');
SET #StreetType = NULLIF( Util.Trim(#StreetType ), '');
SET #StreetPostDir = NULLIF( Util.Trim(#StreetPostDir ), '');
DECLARE #Result VarChar(100) = #StreetNumber;
IF #StreetDir IS NOT NULL BEGIN
IF #Result IS NOT NULL
SET #Result = #Result + ' ' + #StreetDir;
ELSE
SET #Result = #StreetDir;
END
IF #StreetName IS NOT NULL BEGIN
IF #Result IS NOT NULL
SET #Result = #Result + ' ' + #StreetName;
ELSE
SET #Result = #StreetName;
END
IF #StreetType IS NOT NULL BEGIN
IF #Result IS NOT NULL
SET #Result = #Result + ' ' + #StreetType;
ELSE
SET #Result = #StreetType;
END
IF #StreetPostDir IS NOT NULL BEGIN
IF #Result IS NOT NULL
SET #Result = #Result + ' ' + #StreetPostDir;
ELSE
SET #Result = #StreetPostDir;
END
RETURN NULLIF(#Result, '');
END
CREATE FUNCTION [Util].[Trim]
(
#value nVarChar(max)
)
RETURNS nVarChar(max)
AS
BEGIN
RETURN LTrim(RTrim(#value))
END
1) You could create both function WITH SCHEMABINDING:
ALTER FUNCTION dbo.[Trim]
(
#value nVarChar(max)
)
RETURNS nVarChar(max)
WITH SCHEMABINDING
AS
...
and
ALTER FUNCTION dbo.[BuildStreetFullName]
(
#StreetNumber VARCHAR(20),
#StreetDir VARCHAR(2),
#StreetName VARCHAR(50) ,
#StreetType VARCHAR(4) ,
#StreetPostDir VARCHAR(2)
)
RETURNS VarChar(100)
WITH SCHEMABINDING
AS
...
This will force SQL Server to check if these function are deterministic or not.
SELECT OBJECTPROPERTY( OBJECT_ID(N'dbo.[BuildStreetFullName]') , 'IsDeterministic' ) AS IsDeterministic
Output:
IsDeterministic
---------------
1
2) Please don't use != NULL operator to check for NOT NULL. Use IS NOT NULL. At this moment ANSI_NULLS OFF is deprecated and a a future version of SQL Server will allow only ANSI_NULLS ON.
3) Scalar functions can be a nightmare from performance point of view. I would rewrite those functions as inline table valued functions.

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

What is wrong with this statement?
ALTER Function [InvestmentReturn].[getSecurityMinLowForPeriod](#securityid int,
#start datetime,
#end datetime)
returns xml
begin
declare #results varchar(500)
declare #low int
declare #adjustedLow int
declare #day varchar(10)
if #end is null
begin
set #end = getdate()
end
set #adjustedLow = (select min(adjLow)
from (
select Low * [InvestmentReturn].[fn_getCorporateActionSplitFactor](isq.securityid, #start, convert(varchar,day, 111)) as adjLow
from
securityquote isq
where isq.securityid = #securityid and isq.day >= convert(varchar(10), #start, 111) and convert(varchar(10), #end, 111) >= isq.day
and low != -1
) as x)
select
top 1 #low = low
, #day = day
, #adjustedLow
--select high
from
securityquote sq
where
day >= convert(varchar(10), #start, 111) and convert(varchar(10), #end, 111) >= day
and securityid = #securityid and low != -1
order by low asc
set #results= '<results type="debug_min">'
set #results = #results + '<periodStart>' + coalesce(cast(#start as varchar(20)), 'NULL') + '</periodStart>'
set #results = #results + '<periodEnd>' + coalesce(cast(#end as varchar(20)), 'NULL') + '</periodEnd>'
set #results = #results + '<securityID>' + coalesce(cast(#securityID as varchar(10)), 'NULL') + '</securityID>'
set #results = #results + '<periodMin>' + coalesce(cast(#low as varchar(10)), '-11111') + '</periodMin>'
set #results = #results + '<coraxAdjustedPeriodMin>' + coalesce(cast(#adjustedLow as varchar(10)), '-11111') + '</coraxAdjustedPeriodMin>'
set #results = #results + '<dayMinOcurred>' + coalesce(#day, 'NULL') + '</dayMinOcurred>'
set #results = #results + '</results>'
return #results
Just to explain the answer (after getting where the error was caused), I simply removed #adjustedLow from the second select statement.
Column values from the SELECT statement are assigned into #low and #day local variables; the #adjustedLow value is not assigned into any variable and it causes the problem:
The problem is here:
select
top 1 #low = low
, #day = day
, #adjustedLow -- causes error!
--select high
from
securityquote sq
...
Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
You cannot use a select statement that assigns values to variables to also return data to the user
The below code will work fine, because i have declared 1 local variable and that variable is used in select statement.
Begin
DECLARE #name nvarchar(max)
select #name=PolicyHolderName from Table
select #name
END
The below code will throw error "A SELECT statement that assigns a value to a variable
must not be combined with data-retrieval operations" Because we are retriving data(PolicyHolderAddress) from table, but error says data-retrieval operation is not allowed when you use some local variable as part of select statement.
Begin
DECLARE #name nvarchar(max)
select
#name = PolicyHolderName,
PolicyHolderAddress
from Table
END
The the above code can be corrected like below,
Begin
DECLARE #name nvarchar(max)
DECLARE #address varchar(100)
select
#name = PolicyHolderName,
#address = PolicyHolderAddress
from Table
END
So either remove the data-retrieval operation or add extra local variable. This will resolve the error.
declare #cur cursor
declare #idx int
declare #Approval_No varchar(50)
declare #ReqNo varchar(100)
declare #M_Id varchar(100)
declare #Mail_ID varchar(100)
declare #temp table
(
val varchar(100)
)
declare #temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare #slice varchar(8000)
declare #String varchar(100)
--set #String = '1200096,1200095,1200094,1200093,1200092,1200092'
set #String = '20131'
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(',',#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
--select #slice
insert into #temp values(#slice)
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
-- select distinct(val) from #temp
SET #cur = CURSOR FOR select distinct(val) from #temp
--open cursor
OPEN #cur
--fetchng id into variable
FETCH NEXT
FROM #cur into #Approval_No
--
--loop still the end
while ##FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, #ReqNo=Approval_Sr_No,#M_Id=AM_ID,#Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=#Approval_No
insert into #temp2 values(#ReqNo,#M_Id,#Mail_ID)
FETCH NEXT
FROM #cur into #Approval_No
end
--close cursor
CLOSE #cur
select * from #tem

Resources