While loop with += (Addition Assignment) shows just last resoult - sql

I have a sql table for storing temp data
create table TempDataStore (ID int, HtmlCode NVARCHAR(max))
I populate this table with while loop
while #cnt < 3
BEGIN
set #html = CONVERT(nvarchar(MAX),dilos.report.CreateHTMLTable(
(
select * from dilos.report.getHESExpress(cast(#site as varchar))
order by status,SendungsNr offset 0+#cnt*4 rows fetch next 4 rows only FOR XML PATH('row'),ELEMENTS XSINIL),null,'',''))
insert into TempDataStore values(#cnt+1, #html)
set #cnt = #cnt +1
end
This is used to convert sql to html table and divide query results to 4 rows.
Now I want to create a nvarchar(MAX) variable called #htmlSummary to display every row from TempDataStore as one html code (string/nvachar).
while #cnt<3 --just some number
begin
set #htmlSummary = '<p><h3>Express Orders</h3>' +coalesce(replace((select HtmlCode from TempDataStore where id =#cnt+1),'<table border="1" style="font-size:40px;','<table class="table-sm table-striped"'),'') +'</p>'
set #htmlSummary +=#htmlSummary
set #cnt =#cnt+1
END
select #htmlSummary
The problem is that at the end #htmlSummary stores just the last row of TempDataStore table.

Related

T-SQL script to update numerous prod tables from temp tables

I am trying to simplify the updating of numerous production tables from temp tables. I currently have a long script that uses the MERGE command, but as I increase the number of tables to be processed, the MERGE code is getting unwieldy. To simplify, my idea is to create a script that will get the table names into a cursor, get the field names for that table into a different cursor, then compare temp and prod values. If different, I will update the prod table.
The table 'TableManifest' has only 1 column called TableName.
So 2 questions
1 - Is this an efficient approach to the problem? I'd love to get other suggestions.
2 - This code fails with an error "Must declare the table variable #Temp_TableName" on the line that starts with 'IF(SELECT..'.
DECLARE #TableName varchar(MAX) -- TARGET Table to update
DECLARE #Temp_TableName varchar(MAX) -- SOURCE Table for compare
DECLARE #ColumnNames varchar(MAX) -- Table Column to compare
-- Create CURSOR of Tables to process
DECLARE C_TableNames CURSOR FOR SELECT TableName FROM TableManifest
OPEN C_TableNames
-- Get 1st table name
FETCH NEXT FROM C_TableNames INTO #TableName
WHILE ##FETCH_STATUS = 0
BEGIN
-- Create variable for TEMP table name
SELECT #Temp_TableName = CONCAT('TEMP_',#TableName)
-- Create CURSOR of Column Names in the table
DECLARE C_ColumnNames CURSOR FOR SELECT name FROM sys.columns WHERE object_id = OBJECT_ID(#TableName)
OPEN C_ColumNames
-- Get 1st column name
FETCH NEXT FROM C_ColumnNames INTO #ColumnNames
WHILE ##FETCH_STATUS = 0
BEGIN
-- If the column name is not 'ID' and the values are different, update the TARGET table
IF(SELECT #ColumnNames FROM #Temp_TableName) <> (SELECT #ColumnNames FROM #TableName) AND #ColumnNames <> 'id'
UPDATE #TableName SET #ColumnNames = (SELECT #ColumnNames from #Temp_TableName)
-- Get next column name
FETCH NEXT FROM C_ColumnNames INTO #ColumnNames
END
-- Get next table name
FETCH NEXT FROM C_TableNames INTO #TableName
END
-- Clean up
CLOSE C_ColumNames
DEALLOCATE C_ColumNames
CLOSE C_TableNames
DEALLOCATE C_TableNames

Set the temporary table in SQL server as variable

I am trying to create a temporary table but I need to change the name of the table based on the content of a variable as I need to create more than one table inside a while loop. Is there a way to do that?
while(#roCounter <= #insideCounter)
BEGIN
set #nameOfTable = #nameOfTable+#roCounter
select * into ##nameOfTable from #CC where ro=#roCounter --#nameOfTable is a variable
set #roCounter = #roCounter +1
END
Drop Table #CC
set #counter = #counter +1
END

how to sum column i in temp table

SELECT #cinema_count = COUNT(c.[key]) FROM cinemas c
SET #count = 0
WHILE #count < #cinema_count
BEGIN
SET #count = #count+1
SET #buffer = 'ALTER TABLE #temptable ADD cinema'+LTRIM(RTRIM(CAST(#count AS VARCHAR)))+' MONEY DEFAULT 0 WITH VALUES'
EXEC(#buffer)
END
this is my code to alter my #temptable, my #temptable now look like this:
date|cinema1|cinema2|cinema3...to cinema10
i want to sum up the values of my column, the problem is i dont know how to select the cinema from my #temptable
here's my code in selecting the sum of cinema
select #sum = sum('cinema' + CAST(#count as varchar)) from #temptable
Operand data type varchar is invalid for sum operator --error.
hellp me pls..thanks
As you can see from the error message, the string 'cinema' is not being considered as a field name, but as a literal string. So you need to use a string variable to concat the variable name with your SUM query. Should be something like this:
DECLARE #SUM VARCHAR(5000)
SET #SUM = 'SELECT SUM(cinema'+CAST(#count AS VARCHAR(50))+') from #temptable'
EXEC (#SUM)
Test dynamic sql by using PRINT in place of EXEC to make sure the resulting query is correct.
Edit: Added missing parenthesis.

insert the null record in the print lable

I am trying to create a SP which print the label of my vendor, vendor name. I want the user set the startposition, before the startposition I just simply insert a null value. I want be able to reuse the label sheet.
I have the SP code like this:
Alter PROCEDURE [dbo].[z_sp_APVendorLabel]
(#VendorGroup bGroup ,
#StartPosition int)
AS
BEGIN
SET NOCOUNT ON;
Create table #data_null
(Vendor int,
Name varchar(60)null)
Declare #counter int
SET #counter = 0
WHILE #counter < #StartPosition
BEGIN
UPDATE #data_null SET Vendor='',Name=' '
SET #counter = #counter + 1
END
Create table #detial
(Vendor int,
Name varchar (60)null)
select Vendor, Name into #data from APVM
WHERE VendorGroup= #VendorGroup
select * from #data_null
Union All
select * from #detial
END
It is very simple, but when I test it, I did not get any data.
You're creating the table #data_null, and updating it, but never inserting any rows. If you inspect ##rowcount after each update, you'll see it's zero.
Before you change that loop to insert instead of update, please consider setting up a permanent table to select from. A loop to generate N values on every invocation of the procedure is really not the best use of your server's time, or yours. ;-)

process each row in table in stored procedure using cursor

My Scenario is bit different. what i am doing in my stored procedure is
Create Temp Table and insert rows it in using "Cursor"
Create Table #_tempRawFeed
(
Code Int Identity,
RawFeed VarChar(Max)
)
Insert Data in temp table using cursor
Set #GetATM = Cursor Local Forward_Only Static For
Select DeviceCode,ReceivedOn
From RawStatusFeed
Where C1BL=1 AND Processed=0
Order By ReceivedOn Desc
Open #GetATM
Fetch Next
From #GetATM Into #ATM_ID,#Received_On
While ##FETCH_STATUS = 0
Begin
Set #Raw_Feed=#ATM_ID+' '+Convert(VarChar,#Received_On,121)+' '+'002333'+' '+#ATM_ID+' : Bills - Cassette Type 1 - LOW '
Insert Into #_tempRawFeed(RawFeed) Values(#Raw_Feed)
Fetch Next
From #GetATM Into #ATM_ID,#Received_On
End
Now have to process each row in Temp Table using another Cursor
DECLARE #RawFeed VarChar(Max)
DECLARE Push_Data CURSOR FORWARD_ONLY LOCAL STATIC
FOR SELECT RawFeed
FROM #_tempRawFeed
OPEN Push_Data
FETCH NEXT FROM Push_Data INTO #RawFeed
WHILE ##FETCH_STATUS = 0
BEGIN
/*
What Should i write here to retrieve each row one at a time ??
One Row should get stored in Variable..in next iteration previous value should get deleted.
*/
FETCH NEXT FROM Push_Data INTO #RawFeed
END
CLOSE Push_Data
DEALLOCATE Push_Data
Drop Table #_tempRawFeed
What Should i write In BEGIN to retrieve each row one at a time ??
One Row should get stored in Variable..in next iteration previous value should get deleted.
Regarding your last question, if what you are really intending to do within your last cursor is to concatenate RawFeed column values into one variable, you don't need cursors at all. You can use the following (adapted from your SQL Fiddle code):
CREATE TABLE #_tempRawFeed
(
Code Int IDENTITY
RawFeed VarChar(MAX)
)
INSERT INTO #_tempRawFeed(RawFeed) VALUES('SAGAR')
INSERT INTO #_tempRawFeed(RawFeed) VALUES('Nikhil')
INSERT INTO #_tempRawFeed(RawFeed) VALUES('Deepali')
DECLARE #RawFeed VarChar(MAX)
SELECT #RawFeed = COALESCE(#RawFeed + ', ', '') + ISNULL(RawFeed, '')
FROM #_tempRawFeed
SELECT #RawFeed
DROP TABLE #_tempRawFeed
More on concatenating different row values into a single string here: Concatenate many rows into a single text string?
I am pretty sure that you can avoid using the first cursor as well. Please, avoid using cursors, since the really hurt performance. The same result can be achieved using set based operations.