Increment date value in SQL column - sql-server

There is a SQL query:
DECLARE sptv cursor local fast_forward for
SELECT GETDATE() as Time,
r.session_id,
r.cpu_time,
p.physical_io,
t.text,
substring(t.text, r.statement_start_offset/2 + 1, case when r.statement_end_offset = -1 then len(t.text) else (r.statement_end_offset - r.statement_start_offset)/2 end) as text_running,
p.blocked,
db_name(p.dbid) as dbname,
r.status,
r.command,
r.start_time,
r.wait_type,
p.waitresource,
p.status,
p.open_tran,
p.loginame,
p.hostname,
p.program_name,
r.percent_complete,
r.wait_type,
r.last_wait_type,
p.waittime
from sys.dm_exec_requests r
cross apply sys.dm_exec_sql_text(r.sql_handle) t
inner join sys.sysprocesses p on p.spid = r.session_id
open sptv;
while 1 = 1
begin
fetch next from sptv;
if ##fetch_status <> 0
break;
end;
close sptv;
deallocate sptv;
I want the time in the Time column to increase by 1 second for each line. I managed to do it with the following query:
CREATE TABLE #ActibeUser
(
Time DATETIME,
ID int identity(1,1),
session_id INT,
cpu_time INT,
physical_io INT,
text VARCHAR(MAX),
text_running VARCHAR(MAX),
blocked INT,
dbname VARCHAR(MAX),
status1 VARCHAR(MAX),
command VARCHAR(MAX),
start_time DATETIME,
wait_type1 VARCHAR(MAX),
waitresource VARCHAR(MAX),
status2 VARCHAR(MAX),
open_tran INT,
loginame VARCHAR(MAX),
hostname VARCHAR(MAX),
program_name VARCHAR(MAX),
percent_complete INT,
wait_type2 VARCHAR(MAX),
last_wait_type VARCHAR(MAX),
waittime INT
)
INSERT INTO #ActibeUser
(
Time,
session_id,
cpu_time,
physical_io,
text,
text_running,
blocked,
dbname,
status1,
command,
start_time,
wait_type1,
waitresource,
status2,
open_tran,
loginame,
hostname,
program_name,
percent_complete,
wait_type2,
last_wait_type,
waittime
)
SELECT GETDATE() AS Time,
r.session_id,
r.cpu_time,
p.physical_io,
t.text,
substring(t.text, r.statement_start_offset/2 + 1, case when r.statement_end_offset = -1 then len(t.text) else (r.statement_end_offset - r.statement_start_offset)/2 end) as text_running,
p.blocked,
db_name(p.dbid) as dbname,
r.status,
r.command,
r.start_time,
r.wait_type,
p.waitresource,
p.status,
p.open_tran,
p.loginame,
p.hostname,
p.program_name,
r.percent_complete,
r.wait_type,
r.last_wait_type,
p.waittime
from sys.dm_exec_requests r
cross apply sys.dm_exec_sql_text(r.sql_handle) t
inner join sys.sysprocesses p on p.spid = r.session_id
DECLARE sptv cursor local fast_forward for
SELECT * FROM #ActibeUser
open sptv;
while 1 = 1
begin
fetch next from sptv;
if ##fetch_status <> 0
break;
UPDATE #ActibeUser
SET Time = DATEADD(SS,1,Time)
end;
close sptv;
deallocate sptv;
DROP TABLE #ActibeUser
But it does not suit me, I cannot use temporary tables. Help to correct the first request, please.
I transfer the received data to Zabbix, and from it to Grafana.

You can just use DATEADD along with a ROW_NUMBER inside your SELECT.
Also you shouldn't use sys.sysprocesses, it's deprecated. Use sys.dm_exec_sessions instead.
SELECT DATEADD(second, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), GETDATE()) AS Time,
r.session_id,
r.cpu_time,
physical_io = s.reads + s.writes,
t.text,
substring(t.text, r.statement_start_offset/2 + 1, case when r.statement_end_offset = -1 then len(t.text) else (r.statement_end_offset - r.statement_start_offset)/2 end) as text_running,
r.blocking_session_id,
db_name(s.database_id) as dbname,
r.status,
r.command,
r.start_time,
r.wait_type,
r.waitresource,
s.status,
s.open_transaction_count,
s.login_name,
s.host_name,
s.program_name,
r.percent_complete,
r.wait_type,
r.last_wait_type,
r.waittime
from sys.dm_exec_requests r
inner join sys.dm_exec_sessions s on s.session_id = r.session_id
cross apply sys.dm_exec_sql_text(r.sql_handle) t

Related

Check for matches

I have two tables #Cust and #Bh. I need to take the last records from the #Bh table by the "loaddate" field and if there are no matches then insert the records.
#Cust:
DECLARE #Cust TABLE(
Custnumber INT,
Flag NVARCHAR(10),
data NVARCHAR(10),
status NVARCHAR(10),
loaddate DATETIME
)
INSERT #Cust (Custnumber
,Flag
,data
,status
,loaddate)
VALUES (123,N'Y',N'20170117',N'Test','2018-11-15 15:35:26.393')
#Bh:
DECLARE #Bh TABLE(
Custnumber INT,
Flag NVARCHAR(10),
data NVARCHAR(10),
status NVARCHAR(10),
loaddate DATETIME
)
INSERT #Bh (Custnumber
,Flag
,data
,status
,loaddate)
VALUES (123,N'Y',N'20170117',N'','2018-11-09 15:35:26.393')
,(123,N'Y',N'20170117',N'Tests','2018-11-10 15:35:26.393')
,(123,N'Y',N'20170117',N'','2018-11-15 15:35:26.393')
,(123,N'Y',N'20170117',N'Test','2018-11-15 15:35:26.393')
Result:
INSERT INTO #Bh(Custnumber
,Flag
,data
,status
,loaddate)
SELECT DISTINCT PC.Custnumber
,PC.Flag
,PC.data
,PC.status
,PC.loaddate
FROM #Bh AS BH
INNER JOIN #Cust AS PC ON PC.Custnumber = BH.Custnumber
AND (ISNULL(PC.Flag, '''') <> ISNULL(BH.Flag, '''')
OR ISNULL(PC.data, '''') <> ISNULL(BH.data, '''')
OR ISNULL(PC.status, '''') <> ISNULL(BH.status, ''''))
WHERE BH.loaddate = (SELECT MAX(loaddate) FROM #Bh AS BH2 WHERE BH.[Custnumber] = BH2.[Custnumber])';
Because I have not quite the right condition, then insert the record due to the fact that row number 3 is different from the entry in the table #Cust and as a result is added to the table #Bh
Here is a solution that I came up with and it fits my cases, but maybe there is some simpler solution?
WHERE NOT EXISTS(SELECT 1 FROM #Bh AS BH2 WHERE PC.Custnumber = BH2.Custnumber AND PC.Flag = bh2.Flag GROUP BY BH2.Custnumber HAVING CONVERT(varchar(10), max(bh2.[loaddate]), 101) = (SELECT CONVERT(varchar(10), max([loaddate]), 101) FROM #Bh AS BH3 WHERE BH3.Custnumber = BH2.Custnumber))
OR NOT EXISTS(SELECT 1 FROM #Bh AS BH2 WHERE PC.Custnumber = BH2.Custnumber AND PC.data = bh2.data GROUP BY BH2.Custnumber HAVING CONVERT(varchar(10), max(bh2.[loaddate]), 101) = (SELECT CONVERT(varchar(10), max([loaddate]), 101) FROM #Bh AS BH3 WHERE BH3.Custnumber = BH2.Custnumber))
OR NOT EXISTS(SELECT 1 FROM #Bh AS BH2 WHERE PC.Custnumber = BH2.Custnumber AND PC.status = bh2.status GROUP BY BH2.Custnumber HAVING CONVERT(varchar(10), max(bh2.[loaddate]), 101) = (SELECT CONVERT(varchar(10), max([loaddate]), 101) FROM #Bh AS BH3 WHERE BH3.Custnumber = BH2.Custnumber))

How to add rows with null data dynamically in result table in SQL Server 2012?

I have this table with 22 rows as above
I am getting a converted table as above
I created following procedure in order to get result table
ALTER PROCEDURE [dbo].[proc_YS_BAB_IR_Item]
#UserId int
AS
BEGIN TRAN
DECLARE #SqlQry NVARCHAR(MAX);
SET #SqlQry = N''
DECLARE #Cnt INT = 1, #EndCnt INT = 25,
#v_UserId INT = CAST(#UserId AS VARCHAR(MAX));
CREATE TABLE #TempColumns
(
Calculate_ItemIdentifier VARCHAR(MAX),
SeqOrder INT
)
WHILE #cnt <= #EndCnt
BEGIN
INSERT INTO #TempColumns
SELECT
'IR'+ CAST(#Cnt AS VARCHAR(MAX)),
#Cnt
SET #Cnt = #Cnt + 1;
END
DECLARE #DATA VARCHAR(10), #DATA1 VARCHAR(10) = '000000'
DECLARE #zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours
DECLARE #yourTable TABLE ([value] varchar(max))
-- convert array to xml
;WITH cte AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
[response],
CAST('<a>'+REPLACE(SUBSTRING([response],2,LEN([response]) - 2),',','</a><a>')+'</a>' as xml) AS x,
#v_UserId AS UserId,
[item_identifier]
FROM
#TempColumns
LEFT JOIN
YS_BAB_response_dump ON YS_BAB_response_dump.Item_Identifier = #TempColumns.Calculate_ItemIdentifier
AND UserId = CAST(#UserId AS VARCHAR(MAX))
AND TestModel = 'IR'
)
-- do the stuff
SELECT
c.rn,
c.[response],
c.[item_identifier],
RIGHT(#zero_str +
CAST(SUM(CAST(STUFF(#zero_str,t.c.value('.','tinyint')+1,1,'1') AS INT)) AS VARCHAR(6)), 6) AS ans,
c.UserId
FROM
cte c
CROSS APPLY
x.nodes('/a') AS t(c)
GROUP BY
c.rn, c.[response], c.UserId, c.[Item_Identifier]
ORDER BY
c.rn
COMMIT TRAN
What changes I need to do in above procedure to get 25 records as a result instead of 22, For IR21,IR22 and IR25 I want null data in response and ans columns for that respective userId? May i need to use some other function instead of CROSS APPLY? How it will be?
You were almost there. Use OUTER APPLY instead of CROSS APPLY

select query returns empty in sp but when run it alone, it is not empty. Why?

I have a stored procedure that I write to Table and read table. I write with no problem but when I want to read it returns empty. but it is not empty when I select query and run it returns data. Why it can be.
Here is my codes. I give fulltext index Dump and TempTable to tag,title and body columns.
IF LEFT(#splitdata,1) = '#'
BEGIN
SET #splitdata = (SELECT REPLACE(#splitdata,'#',''))
INSERT INTO [WebTR].[dbo].[TempTable]
SELECT p.*
FROM [WebTR].[dbo].[Dump] AS p
INNER JOIN containstable([WebTR].[dbo].[Dump], tags, #splitdata) AS k
ON p.dumpID = k.[key]
end
SET #replacedLast += #replaced2
FETCH NEXT FROM TableA_cursor INTO #row
I insert temptable first then
IF EXISTS(SELECT * FROM WebTR.dbo.TempTable)
BEGIN
SELECT #replacedLast AS withtag
select dumpId,title,source,tags,creationdate,status,body,createdBy,max(rank) as rank,'olsanaaa' AS sinir
from
((SELECT p.*, k.rank
FROM WebTR.dbo.TempTable AS p
INNER JOIN containstable(WebTR.dbo.TempTable, title,'"*cunku*"' ) AS k
ON p.dumpID = k.[key]
)
union
(
SELECT p.*, k.rank
FROM WebTR.dbo.TempTable AS p
INNER JOIN containstable(WebTR.dbo.TempTable, body, '"*cunku*"') AS k
ON p.dumpID = k.[key]
))y group by dumpId,title,source,tags,creationdate,status,body,createdBy
order by rank DESC
END
as you can see in that if block when I select only select query it returns data but when execute stored procedure it returns empty even it enters the if block
here is he full sp:
USE [WebTR]
GO
/****** Object: StoredProcedure [dbo].[search] Script Date: 10.6.2015 16:19:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[search]
#param1 varchar(250)
AS
BEGIN
declare #searchString varchar(250)
set #searchString = LTrim(RTrim(#param1))
TRUNCATE TABLE [WebTR].[dbo].[TempTable]
--SELECT ROW_NUMBER() OVER(ORDER BY #param1 ASC) AS row , * INTO #temp1 from WebTR.dbo.fnsplitstring(#searchString ,'')
SELECT ROW_NUMBER() OVER(ORDER BY CAST(SUBSTRING(splitdata, 0, 2) AS CHAR(1)) desc) AS row,* INTO #params from WebTR.dbo.fnsplitstring(#searchString ,'')
SET NOCOUNT ON
DECLARE #row INT
DECLARE #splitdata VARCHAR(50)
DECLARE #replaced1 VARCHAR(500)
DECLARE #replaced2 VARCHAR(500)
DECLARE #replacedLast VARCHAR(500)
DECLARE #last VARCHAR(500)
DECLARE TableA_cursor CURSOR FOR SELECT row FROM #params
SET #last = (SELECT COUNT(*) FROM #params)
SET #replacedLast = ''
OPEN TableA_cursor
FETCH NEXT FROM TableA_cursor INTO #row
WHILE ##FETCH_STATUS = 0
BEGIN
SET #splitdata = (SELECT splitdata FROM #params WHERE row=#row)
IF LEFT(#splitdata,1) = '#'
BEGIN
SET #splitdata = (SELECT REPLACE(#splitdata,'#',''))
BEGIN TRANSACTION
INSERT INTO [WebTR].[dbo].[TempTable]
SELECT p.*
FROM [WebTR].[dbo].[Dump] AS p
INNER JOIN containstable([WebTR].[dbo].[Dump], tags, #splitdata) AS k
ON p.dumpID = k.[key]
COMMIT TRANSACTION
end
ELSE
begin
IF LEFT(#splitdata,1)='-'
BEGIN
IF RIGHT(#replacedLast,4) = 'AND '
BEGIN
SET #replaced1 =('NOT ')
END
ELSE
BEGIN
SET
#replaced1 =('NOT ')
end
SET #replaced2= #replaced1 + (SELECT REPLACE (#splitdata, '-', '"*'))
SET #replaced2= #replaced2 + '*" ' + 'AND '
END
ELSE
BEGIN
SET #replaced2 =('"*')
SET #replaced2 = #replaced2 + (SELECT #splitdata + '*" AND ')
END
SET #replacedLast += #replaced2
END
FETCH NEXT FROM TableA_cursor INTO #row
IF ##FETCH_STATUS !=0
BEGIN
IF RIGHT(#replacedLast,4)='AND '
BEGIN
SET #replacedLast =LEFT(#replacedLast,(LEN(#replacedLast)-3))
END
END
END
CLOSE TableA_cursor
DEALLOCATE TableA_cursor
IF EXISTS(SELECT * FROM WebTR.dbo.TempTable)
BEGIN
SELECT #replacedLast AS withtag
select dumpId,title,source,tags,creationdate,status,body,createdBy,max(rank) as rank,'olsanaaa' AS sinir
from
((SELECT p.*, k.rank
FROM WebTR.dbo.TempTable AS p
INNER JOIN containstable(WebTR.dbo.TempTable, title,'"*cunku*"' ) AS k
ON p.dumpID = k.[key]
)
union
(
SELECT p.*, k.rank
FROM WebTR.dbo.TempTable AS p
INNER JOIN containstable(WebTR.dbo.TempTable, body, '"*cunku*"') AS k
ON p.dumpID = k.[key]
))y group by dumpId,title,source,tags,creationdate,status,body,createdBy
order by rank DESC
END
ELSE
BEGIN
select * into #temp1
from
((SELECT p.*, k.rank
FROM [WebTR].[dbo].[Dump] AS p
INNER JOIN containstable([WebTR].[dbo].[Dump], title, #replacedLast) AS k
ON p.dumpID = k.[key]
)
union
(
SELECT p.*, k.rank
FROM [WebTR].[dbo].[Dump] AS p
INNER JOIN containstable([WebTR].[dbo].[Dump], body, #replacedLast) AS k
ON p.dumpID = k.[key]
))x
select dumpId,title,source,tags,creationdate,status,body,createdBy,max(rank) as rank
from #temp1 with (NOLOCK)
group by dumpId,title,source,tags,creationdate,status,body,createdBy
order by rank DESC
DROP TABLE #temp1
end
END
CLOSE TableA_cursor
DEALLOCATE TableA_cursor
did you checked this part ? Because your cursor is closing before some actions.
I have this misbehaviour in SQL Server 2008 too. If you insert and retrieve too fast with fulltext index your query won't result in the new queries.
Maybe you need a manual population of your fulltext index.
See example based on AdventureWorks
ALTER FULLTEXT INDEX ON HumanResources.JobCandidate START UPDATE POPULATION;
GO
https://technet.microsoft.com/en-us/library/ms142575.aspx
Hopefully the Population update will fix your issue.
Best regards,
Ionic

Can I create a View of Function from a Temp Table

Can I create a view or function using the below query? It uses temp tables. I am not able to create either a view or function.
--TEmp table--
IF OBJECT_ID('tempdb..#Enquiries') IS NOT NULL
DROP TABLE #Enquiries
GO
CREATE TABLE #Enquiries
(ID INT,PID INT,Name VARCHAR(50),Enquiries INT,EnquiryDate datetime)
INSERT INTO #Enquiries
SELECT ROW_NUMBER()
OVER (ORDER BY ProjectName) AS Row, (SELECT top 1 ITEM FROM DBO.split(e.InterestedProjects,',')) as Projects,P.ProjectName,COUNT(CAST(EnquiryDate AS DATE)) AS Enquiries,CAST(EnquiryDate AS DATE) AS EnquiryDate
FROM tbl_Enquiry e INNER JOIN
tbl_Projects AS P ON P.ProjectId = (SELECT TOP 1 ITEM FROM DBO.split(e.InterestedProjects,','))
WHERE e.IsActive=1 and e.isdeleted=0 AND p.IsActive=1 AND p.IsDeleted=0 AND P.ProjectId IN (SELECT TOP 1 ITEM FROM DBO.split(e.InterestedProjects,','))
GROUP BY e.InterestedProjects,P.ProjectName,CAST(EnquiryDate AS DATE)
--SiteVisits
IF OBJECT_ID('tempdb..#SiteVisit') IS NOT NULL
DROP TABLE #SiteVisit
GO
CREATE TABLE #SiteVisit
(ID INT,PID INT,Name VARCHAR(50),Sitevisits INT,PickUpDatetime datetime)
INSERT INTO #SiteVisit
SELECT ROW_NUMBER() OVER (ORDER BY ProjectName) AS Row,s.ProjectId,p.ProjectName As Name,count(sd.PickUpDatetime) AS Sitevisits,CAST(PickUpDatetime AS DATE) AS PickUpDatetime FROM tbl_SiteVisit s
INNER JOIN tbl_SiteVisitDetails sd ON s.SiteVisitId=sd.SiteVisitId
INNER JOIN tbl_Projects p ON p.ProjectId=s.ProjectId
WHERE s.IsActive=1 and s.isdeleted=0 AND sd.isactive=1 AND sd.isdeleted=0
GROUP BY s.ProjectId,sd.PickUpDatetime,p.ProjectName,CAST(PickUpDatetime AS DATE)
--Bookings
IF OBJECT_ID('tempdb..#Bookings') IS NOT NULL
DROP TABLE #Bookings
GO
CREATE TABLE #Bookings
(ID INT,PID INT,Name VARCHAR(50),Bookings INT,BookingDate datetime,Revenue money,Area float)
INSERT INTO #Bookings
SELECT ROW_NUMBER() OVER (ORDER BY ProjectName) AS Row, u.ProjectId AS ProjectId,p.ProjectName,count(u.ProjectId) AS Bookings,CAST(b.BookingDate AS DATE) AS BookingDate,SUM(b.TotalAmount) AS [Revenue],SUM(u.UnitArea) AS [Area] FROM tbl_Bookings b
INNER JOIN tbl_Unit u ON b.UnitId=u.UnitId
INNER JOIN tbl_Projects p on p.ProjectId=u.ProjectId
WHERE b.IsActive=1 AND b.IsDeleted=0 and u.IsActive=1 AND u.IsDeleted=0 AND u.Status = 'B'
GROUP BY u.ProjectId,p.ProjectName,CAST(b.BookingDate AS DATE),b.TotalAmount,u.UnitArea
--ORDER BY u.ProjectId
IF OBJECT_ID('tempdb..#T1') IS NOT NULL
DROP TABLE #T1
create TABLE #T1 (
PrimaryNo INT,
EnquiryDate Date,
Enquiries INT,
SiteVisits INT,
Bookings INT,
Revenue Money,
Area Float,
PID INT,
ProjectName nvarchar(max)
)
INSERT INTO #T1(PrimaryNo,EnquiryDate,Enquiries,PID,ProjectName)
SELECT ID,EnquiryDate,sum(enquiries) AS Enquiries,PID,Name FROM #Enquiries GROUP BY id,pid,Name,enquirydate
DECLARE #SVDate date
DECLARE #SV11 INT
DECLARE #BookingDate Date
DECLARE #Bookings11 INT
DECLARE #Revenue11 MONEY
DECLARE #Area11 FLOAT
DECLARE #intFlag_pw11 INT
SET #intFlag_pw11 = 1
DECLARE #TableCntw11 INT
DECLARE #Date Date
DECLARE Cur_SiteVisit CURSOR FAST_FORWARD FOR
SELECT PickUpDatetime FROM #SiteVisit
OPEN Cur_SiteVisit
FETCH NEXT FROM Cur_SiteVisit INTO #Date
DECLARE #ProjectId INT
DECLARE #Count INT = 1
WHILE ##FETCH_STATUS = 0
BEGIN
SET #ProjectId = (SELECT PID FROM #SiteVisit WHERE ID = #Count)
SET #SVDate = ISNULL((SELECT CAST(PickUpDatetime AS DATE) FROM #SiteVisit
WHERE CAST(PickUpDatetime AS DATE) = #Date AND PID = #ProjectId
GROUP BY PickUpDatetime),'-')
SET #SV11 = ISNULL((SELECT Sitevisits FROM #SiteVisit
WHERE CAST(PickUpDatetime AS DATE) = #Date AND PID = #ProjectId
GROUP BY Sitevisits),0)
EXEC ('UPDATE #T1 SET SiteVisits = ' + #SV11 + ' WHERE EnquiryDate = ' + ''''+ #SVDate +''' AND PID =' + #ProjectId)
FETCH NEXT FROM Cur_SiteVisit INTO #Date
SET #Count = #Count + 1
END
CLOSE Cur_SiteVisit
DEALLOCATE Cur_SiteVisit
--For Bookings
DECLARE #Date1 Date
DECLARE Cur_Bookings CURSOR FAST_FORWARD FOR
SELECT BookingDate FROM #Bookings
OPEN Cur_Bookings
FETCH NEXT FROM Cur_Bookings INTO #Date1
DECLARE #ProjectId1 INT
DECLARE #Count1 INT = 1
WHILE ##FETCH_STATUS = 0
BEGIN
SET #ProjectId1 = (SELECT PID FROM #Bookings WHERE ID = #Count1)
SET #Bookings11 = ISNULL((SELECT TOP 1 Bookings FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY Bookings),0)
SET #BookingDate = ISNULL((SELECT TOP 1 CAST(BookingDate AS DATE) FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY CAST(BookingDate AS DATE)),'-')
SET #Revenue11 = ISNULL((SELECT TOP 1 Revenue FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY Revenue),0)
SET #Area11 = ISNULL((SELECT TOP 1 Area FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY Area),0)
EXEC ('UPDATE #T1 SET Bookings = ' + #Bookings11 + ',Revenue=' + #Revenue11 + ',Area = ' + #Area11 + ' WHERE EnquiryDate = ' + '''' + #BookingDate + ''' AND PID =' + #ProjectId1)
FETCH NEXT FROM Cur_Bookings INTO #Date1
SET #Count1 = #Count1 + 1
END
CLOSE Cur_Bookings
DEALLOCATE Cur_Bookings
Select * from #T1
You can't create a view from that, if only because you're doing a number of inserts and other actions. A view is created from a single query.
With regard to user-defined functions: you cannot use dynamic SQL, which you are doing:
EXEC ('UPDATE #T1 SET Bookings = ' + #Bookings11 + ',Revenue=' + #Revenue11 +
',Area = ' + #Area11 + ' WHERE EnquiryDate = ' + '''' + #BookingDate +
''' AND PID =' + #ProjectId1)
You also can't use temp tables. Both of these limitations are documented here: http://msdn.microsoft.com/en-us/library/ms191320.aspx.
But, you can do all of these things in a stored procedure. It is also possible to direct the output of a stored procedure to a temp table or table variable, allowing you to use the output in another query:
INSERT INTO dbo.MyTable
(MyTableId, Column1, Column2) -- arbitrary-chosen column names
EXEC dbo.MyStoredProcedure
SELECT *
FROM dbo.MyTable
WHERE Column1 = 'Some Value'
Finally, you might be able to rework your SQL to work with table variables rather than temp tables, which are allowed. It also looked to me like your dynamic SQL didn't need to be dynamic, so you might be able to eliminate that as well.
Hope this helps.

Insert data into different tables in stored procedure

Following is the original SP which always inserts into table1 (INSERT INTO table1). Now I need to insert either into table1 or table2 which both have the same structure.
I tried to pass the tableName as parameter into SP.
ALTER PROCEDURE [dbo].[sp_importStats] (
#accountID BIGINT,
#csvFileName VARCHAR (1024),
#csvFormatFileName VARCHAR (1024)
#tableName VARCHAR(256))
Then I tried to INSERT using EXECUTE as following:
--Incorrect syntax near EXECUTE.
EXECUTE(
'INSERT INTO '+ #tableName + '(accountId, date, cost)
(SELECT cte.id, ms.date, ms.cost
FROM #stats ms
INNER JOIN CTE cte ON ms.accountNumber = cte.key4)');
Then I tried this:
--Must declare the table variable #tableName.
INSERT INTO #tableName (accountId, date, cost)
(SELECT cte.id, ms.date, ms.cost
FROM #stats ms
INNER JOIN CTE cte ON ms.accountNumber = cte.key4);
Then I tried not to pass the tableName and instead pass a boolean into SP and based on that decide which table I need to insert to:
ALTER PROCEDURE [dbo].[sp_importStats] (
#accountID BIGINT,
#csvFileName VARCHAR (1024),
#csvFormatFileName VARCHAR (1024),
#condition BIT = 0)
IF (#condition= 0)
SET #table = 'table1'
ELSE
SET #table = 'table2'
--Must declare the table variable "#table".
INSERT INTO #table (accountId, date, cost)
(SELECT cte.id, ms.date, ms.cost
FROM #sats ms
INNER JOIN CTE cte ON ms.accountNumber = cte.key4);
I got error either way. Would you please let me know what's the best way to handle this? Why am I receiving these errors? Any help is greatly appreciated.
Original SP:
ALTER PROCEDURE [dbo].[sp_importStats] (
#accountID BIGINT,
#csvFileName VARCHAR (1024),
#csvFormatFileName VARCHAR (1024))
AS
BEGIN
CREATE TABLE #stats(
[accountID] [bigint] NOT NULL,
[accountNumber] [varchar](30) NULL,
[date] [datetime] NOT NULL,
[cost] [money] NULL,
);
EXECUTE('INSERT INTO #stats SELECT * FROM '+
'OPENROWSET (BULK N''' + #csvFileName + '''' +
',FORMATFILE='''+#csvFormatFileName+''''+
',FIRSTROW=2'+
',MAXERRORS=0'+
') AS t;');
WITH CTE(id, key4) AS (
SELECT A.id, A.[key4]
FROM VA A (NOLOCK)
WHERE A.id = #accountID
UNION ALL
SELECT A.id, A.[key4]
FROM VA A (NOLOCK)
INNER JOIN CTE ON (CTE.id = A.MAID)
WHERE A.key4 IS NOT NULL
)
INSERT INTO table1 (accountId, date, cost)
(SELECT cte.id, ms.date, ms.cost
FROM #stats ms
INNER JOIN CTE cte ON ms.accountNumber = cte.key4);
DROP TABLE #stats;
END
This is what I have now:
ALTER PROCEDURE [dbo].[sp_importStats] (
#accountID BIGINT,
#csvFileName VARCHAR (1024),
#csvFormatFileName VARCHAR (1024)
#tableName VARCHAR(256))
AS
BEGIN
DECLARE #sql NVARCHAR(MAX);
CREATE TABLE #stats(
[accountID] [bigint] NOT NULL,
[accountNumber] [varchar](30) NULL,
[date] [datetime] NOT NULL,
[cost] [money] NULL,
);
EXECUTE('INSERT INTO #stats SELECT * FROM '+
'OPENROWSET (BULK N''' + #csvFileName + '''' +
',FORMATFILE='''+#csvFormatFileName+''''+
',FIRSTROW=2'+
',MAXERRORS=0'+
') AS t;');
WITH CTE(id, key4) AS (
SELECT A.id, A.[key4]
FROM VA A (NOLOCK)
WHERE A.id = #accountID
UNION ALL
SELECT A.id, A.[key4]
FROM VA A (NOLOCK)
INNER JOIN CTE ON (CTE.id = A.MAID)
WHERE A.key4 IS NOT NULL
)
--Incorect synstax near SET.
SET #sql = 'INSERT INTO '+ QUOTENAME(#tableName) + '(accountId, date, cost)
(SELECT cte.id, ms.date, ms.cost
FROM #stats ms
INNER JOIN CTE cte ON ms.accountNumber = cte.key4)';
EXECUTE sp_executesql #sql;
DROP TABLE #stats;
END
Passing Table Name as Parameter
Use QUOTENAME() Function to put square brackets around your table names to tell sql server explicitly that it is a Sql Server Object name something like this ..
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N';WITH CTE(id, key4) AS (
SELECT A.id, A.[key4]
FROM VA A (NOLOCK)
WHERE A.id = #accountID
UNION ALL
SELECT A.id, A.[key4]
FROM VA A (NOLOCK)
INNER JOIN CTE ON (CTE.id = A.MAID)
WHERE A.key4 IS NOT NULL
)
INSERT INTO ' + QUOTENAME(#tableName) +' (accountId, date, cost)
SELECT cte.id, ms.date, ms.cost
FROM #stats ms
INNER JOIN CTE cte ON ms.accountNumber = cte.key4;'
EXECUTE sp_executesql #Sql
Using QUOTENAME() Function can protect you against a possible sql injection attack. Also you do not need parenthesis around your select statement.
Also you should avoid using sp_ prefix for you stored Procedure names. Read Here why.
Using IF..ELSE Blocks
IF (Some_Condition IS TRUE)
BEGIN
/* Insert Statement For Table One*/ --<-- No need to use table Names as variable
END -- just hardcode the table names in your
ELSE -- Insert Statements
BEGIN
/* Insert Statement For Table Two*/
END
Did you notice that you missed a comma in declaration.
ALTER PROCEDURE [dbo].[sp_importStats] (
#accountID BIGINT,
#csvFileName VARCHAR (1024),
#csvFormatFileName VARCHAR (1024),---comma missing here
#tableName VARCHAR(256))

Resources