SQL Server 2008 Using while loop to populate missing values - sql-server-2008

This is my table as is:
For each instance of Patient Arrive, I need an instance of the other status. As you can see in this particular scenario, I have 3 patient arrive input; therefore, my status should be as follow table 2:
Here's what I have done so far.
DECLARE #Patient_Leave TABLE
(
id INT,
status VARCHAR (200)
,times VARCHAR (200)
)
DECLARE #arrive INT = 0
DECLARE #Leave INT
set #Patient_Leave = (select ((select COUNT(status) FROM Parameters VF WITH (NOLOCK) where status ='Patient Arrive) -
(select COUNT(status) FROM Parameters VF WITH (NOLOCK) where status='Patient leave')))
WHILE ( #arrive ) < #Leave
BEGIN
INSERT INTO #Patient_Leave
select distinct id, status, (select 'No data entered')as Time FROM Parameters VF WITH (NOLOCK) where status='Patient Leave
SET #arrive = #arrive + 1
END
SELECT * FROM #Patient_Leave
GO

Bethony,
I've build the following based off your provided data and tested to success.
SQL Code:
USE SO_Tests
GO
--CREATE TABLE Patient_Table
-- (
-- id INT
-- ,status VARCHAR (200)
-- ,times VARCHAR(200)
-- )
TRUNCATE TABLE Patient_Table
INSERT INTO
Patient_Table
(ID, status, times)
VALUES
(123666,'Patient Arrive', '20180606 10:52')
,(123666,'Patient Arrive', '20180606 11:21')
,(123666,'Patient Arrive', '20180606 11:45')
,(123666,'Patient Prepped', '20180606 10:52')
,(123666,'Patient Prepped', '20180606 11:45')
,(123666,'Patient Leave', '20180606 10:52')
,(123666,'Patient Return', '20180606 10:55')
,(123666,'Patient Return', '20180606 12:30')
,(123666,'Patient Ready', '20180606 12:45')
,(123666,'Patient Discharged', '20180606 12:45')
SELECT * FROM Patient_Table
DECLARE #Count_Arrive INT = (SELECT COUNT(*) FROM Patient_Table WHERE status = 'Patient Arrive')
DECLARE #Count_Leave INT = (SELECT COUNT(*) FROM Patient_Table WHERE status = 'Patient Leave')
DECLARE #Count_Prepped INT = (SELECT COUNT(*) FROM Patient_Table WHERE status = 'Patient Prepped')
DECLARE #Count_Return INT = (SELECT COUNT(*) FROM Patient_Table WHERE status = 'Patient Return')
DECLARE #Count_Discharged INT = (SELECT COUNT(*) FROM Patient_Table WHERE status = 'Patient Discharged')
DECLARE #Count_Ready INT = (SELECT COUNT(*) FROM Patient_Table WHERE status = 'Patient Ready')
WHILE(#Count_Arrive <> #Count_Leave OR #Count_Arrive <> #Count_Prepped OR #Count_Arrive <> #Count_Return OR #Count_Arrive <> #Count_Discharged OR #Count_Arrive <> #Count_Ready)
BEGIN
IF (#Count_Arrive <> #Count_Leave)
BEGIN
INSERT INTO
Patient_Table
SELECT
123456,
'Patient Leave',
'No Data Provided'
SET #Count_Leave = #Count_Leave + 1
END
IF (#Count_Arrive <> #Count_Prepped)
BEGIN
INSERT INTO
Patient_Table
SELECT
123456,
'Patient Prepped',
'No Data Provided'
SET #Count_Prepped = #Count_Prepped + 1
END
IF (#Count_Arrive <> #Count_Return)
BEGIN
INSERT INTO
Patient_Table
SELECT
123456,
'Patient Return',
'No Data Provided'
SET #Count_Return = #Count_Return + 1
END
IF (#Count_Arrive <> #Count_Discharged)
BEGIN
INSERT INTO
Patient_Table
SELECT
123456,
'Patient Discharged',
'No Data Provided'
SET #Count_Discharged = #Count_Discharged + 1
END
IF (#Count_Arrive <> #Count_Ready)
BEGIN
INSERT INTO
Patient_Table
SELECT
123456,
'Patient Ready',
'No Data Provided'
SET #Count_Ready = #Count_Ready + 1
END
END
SELECT * FROM Patient_Table ORDER BY STATUS
Results:
This covers the additional statuses where needed and applies dummy rows to the count of the arrival rows
UPDATE:
Added in the cursor to progress through the Patient ID's and added some additional handling to prevent adding lines that were never originally recorded and avoiding infinite loop if another status has more row than Patient_Arrive has per id
USE SO_Tests
GO
DECLARE #Patient_Table TABLE
(
id INT
,status VARCHAR (200)
,times VARCHAR(200)
)
--TRUNCATE TABLE Patient_Table
--INSERT INTO
-- Patient_Table
-- (ID, status, times)
--VALUES
-- (123666,'Patient Arrive', '20180606 10:52')
-- ,(123666,'Patient Arrive', '20180606 11:21')
-- ,(123666,'Patient Arrive', '20180606 11:45')
-- ,(123666,'Patient Prepped', '20180606 10:52')
-- ,(123666,'Patient Prepped', '20180606 11:45')
-- ,(123666,'Patient Leave', '20180606 10:52')
-- ,(123666,'Patient Return', '20180606 10:55')
-- ,(123666,'Patient Return', '20180606 12:30')
-- ,(123666,'Patient Ready', '20180606 12:45')
-- ,(123666,'Patient Discharged', '20180606 12:45')
INSERT INTO #Patient_Table SELECT * FROM Patient_Table
DECLARE #id INT
DECLARE Patient_Cursor CURSOR FOR
SELECT
id
FROM
#Patient_Table
OPEN Patient_Cursor
FETCH NEXT FROM Patient_Cursor INTO #id
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Count_Arrive INT = (SELECT COUNT(*) FROM #Patient_Table WHERE status = 'Patient Arrive' AND id = #id)
DECLARE #Count_Leave INT = (SELECT COUNT(*) FROM #Patient_Table WHERE status = 'Patient Leave' AND id = #id)
DECLARE #Count_Prepped INT = (SELECT COUNT(*) FROM #Patient_Table WHERE status = 'Patient Prepped' AND id = #id)
DECLARE #Count_Return INT = (SELECT COUNT(*) FROM #Patient_Table WHERE status = 'Patient Return' AND id = #id)
DECLARE #Count_Discharged INT = (SELECT COUNT(*) FROM #Patient_Table WHERE status = 'Patient Discharged' AND id = #id)
DECLARE #Count_Ready INT = (SELECT COUNT(*) FROM #Patient_Table WHERE status = 'Patient Ready' AND id = #id)
WHILE((#Count_Arrive > #Count_Leave and #Count_Leave > 0) OR (#Count_Arrive > #Count_Prepped and #Count_Prepped > 0) OR (#Count_Arrive > #Count_Return and #Count_Return = 0) OR (#Count_Arrive > #Count_Discharged and #Count_Discharged > 0) OR (#Count_Arrive > #Count_Ready and #Count_Ready > 0))
BEGIN
print 'recursing'
print #count_arrive
print #count_leave
print #count_prepped
print #count_return
print #count_discharged
print #count_ready
IF (#Count_Arrive > #Count_Leave and #Count_Leave > 0)
BEGIN
INSERT INTO
#Patient_Table
SELECT
#id,
'Patient Leave',
'No Data Provided'
SET #Count_Leave = #Count_Leave + 1
END
IF (#Count_Arrive > #Count_Prepped and #Count_Prepped > 0)
BEGIN
INSERT INTO
#Patient_Table
SELECT
#id,
'Patient Prepped',
'No Data Provided'
SET #Count_Prepped = #Count_Prepped + 1
END
IF (#Count_Arrive > #Count_Return and #Count_Return > 0)
BEGIN
INSERT INTO
#Patient_Table
SELECT
#id,
'Patient Return',
'No Data Provided'
SET #Count_Return = #Count_Return + 1
END
IF (#Count_Arrive > #Count_Discharged and #Count_Discharged > 0)
BEGIN
INSERT INTO
#Patient_Table
SELECT
#id,
'Patient Discharged',
'No Data Provided'
SET #Count_Discharged = #Count_Discharged + 1
END
IF (#Count_Arrive > #Count_Ready and #Count_Ready > 0)
BEGIN
INSERT INTO
#Patient_Table
SELECT
#id,
'Patient Ready',
'No Data Provided'
SET #Count_Ready = #Count_Ready + 1
END
END
FETCH NEXT FROM Patient_Cursor INTO #id
END
SELECT * FROM Patient_Table
SELECT * FROM #Patient_Table

I don’t believe you need a cursor for this (although it might be more efficient to use one). This gives you what you need, I think.
WITH Pnumbered AS (
SELECT
P.ID, P.status, P.times, ROW_NUMBER() OVER (
PARTITION BY P.ID, P.status
ORDER BY P.times
) AS rn
FROM Patient_Table AS P
), PA AS (
SELECT
P.ID, P.status, P.times
FROM Patient_Table AS P
WHERE P.status = 'Patient Arrive'
), Enough AS (
SELECT PA.ID, S.status, S.statusseq, ROW_NUMBER() OVER (
PARTITION BY PA.ID, S.status
ORDER BY PA.times
) AS rn FROM PA
CROSS JOIN (
SELECT 'Patient Arrive',1 UNION ALL
SELECT 'Patient Prepped',2 UNION ALL
SELECT 'Patient Leave',3 UNION ALL
SELECT 'Patient Return',4 UNION ALL
SELECT 'Patient Ready',5 UNION ALL
SELECT 'Patient Discharged',6
) AS S(status,statusseq)
)
SELECT
Enough.ID, COALESCE(Pnumbered.status, Enough.status) as status, COALESCE(Pnumbered.times,'No Data Provided') AS times
FROM Pnumbered
RIGHT OUTER JOIN Enough
ON Pnumbered.ID = Enough.ID
AND Pnumbered.status = Enough.status
AND Pnumbered.rn = Enough.rn
ORDER BY ID, statusseq
The idea is as follows: Create a table with each patient ID and each status copied as many times as there are 'Arrive' rows for that ID, and number the copies. Also number the rows of the Patient_Data table that have the same (ID, status) in order by time. Finally, outer-join these two tables, so you get the right number of copies of each (ID,status), and replace the NULL you get from unmatched rows in the outer join with 'Data Not Provided'. (The unmatched rows will be those with a given ID and status that exceed the number of actual rows for that (ID,status) in the Patient_Data table.
If you create a Statuses table for what I’ve derived as S(status,statusseq), the query will look a bit simpler.
Here’s the output:
ID status times
----------- ------------------ -------------------
123666 Patient Arrive 20180606 10:52
123666 Patient Arrive 20180606 11:21
123666 Patient Arrive 20180606 11:45
123666 Patient Prepped 20180606 10:52
123666 Patient Prepped 20180606 11:45
123666 Patient Prepped No Data Provided
123666 Patient Leave 20180606 10:52
123666 Patient Leave No Data Provided
123666 Patient Leave No Data Provided
123666 Patient Return No Data Provided
123666 Patient Return 20180606 10:55
123666 Patient Return 20180606 12:30
123666 Patient Ready 20180606 12:45
123666 Patient Ready No Data Provided
123666 Patient Ready No Data Provided
123666 Patient Discharged No Data Provided
123666 Patient Discharged No Data Provided
123666 Patient Discharged 20180606 12:45
123667 Patient Arrive 20180607 10:52
123667 Patient Prepped No Data Provided
123667 Patient Leave No Data Provided
123667 Patient Return No Data Provided
123667 Patient Ready No Data Provided
123667 Patient Discharged No Data Provided

Related

Using Two Stored Procedure - One get , One update ; But despite records being big, but updated rows = 0, is there anything wrong with my code?

Get All selected players, then for each player loop 2nd procedure:
CREATE DEFINER=`adrian.ng`#`xx.xx.23.151` PROCEDURE `test_dev_00`.`LoopPlayerFirstDpt`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE thisPlayer BIGINT(20) UNSIGNED;
DECLARE counts BIGINT;
DECLARE cur1 CURSOR FOR SELECT COUNT(*), uid FROM ((SELECT dno, uid, utype, bcid, amount, remark, created, transtype, status, updated, dealremark, acode,
actual, ddeals, ufinish, ddomain, userbank, deposituser, ischk, ano, ppid, optionid, cardnum, agentid, platform, currency, brandid
FROM test_deposit_requisition WHERE status = 33 AND (currency = '' OR currency = 'CNY')
ORDER BY created) UNION (SELECT id AS dno, uid, 1 AS utype, 0 AS bcid, amount, remark, created, 0 AS transtype,
33 AS status, updated, remark AS dealremark, 0 AS acode, amount AS actual, 0 AS ddeals, 0 AS ufinish, '' AS ddomain, '' AS userbank,
'' AS deposituser, 0 AS ischk, 0 AS ano, 0 AS ppid, 0 AS optionid, '' AS cardnum, 0 AS agentid, '' AS platform, currency, brandid
FROM test_member_manual_adjust WHERE btype = 1234 AND (currency = '' OR currency = 'CNY')
ORDER BY created)) x GROUP BY uid having count(*) >0 and count(*) <3 ORDER BY x.created;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO counts, thisPlayer;
IF NOT done THEN
CALL UpdateFirstDpt(#thisPlayer);
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
END
and here's the UpdateFirstDpt Procedure that were called: (for each player, get the data, insert into table)
CREATE PROCEDURE test_dev_00.UpdateFirstDpt(IN thisPlayer BIGINT(20) UNSIGNED)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE a, b BIGINT(20) UNSIGNED;
DECLARE c TINYINT(1) UNSIGNED;
DECLARE d DECIMAL(20,8);
DECLARE e,f INT(10) UNSIGNED;
DECLARE g TINYINT(1) UNSIGNED;
DECLARE cur1 CURSOR FOR SELECT dno, uid, 0 as dptype, actual as amount, created, UNIX_TIMESTAMP(NOW()) as updated, 0 as status FROM ((SELECT dno, uid, utype, bcid, amount, remark, created, transtype, status, updated, dealremark, acode,
actual, ddeals, ufinish, ddomain, userbank, deposituser, ischk, ano, ppid, optionid, cardnum, agentid, platform, currency, brandid
FROM test_deposit_requisition WHERE status = 33 AND uid = thisPlayer AND (currency = '' OR currency = 'CNY')
LIMIT 1) UNION (SELECT id AS dno, uid, 1 AS utype, 0 AS bcid, amount, remark, created, 0 AS transtype,
33 AS status, updated, remark AS dealremark, 0 AS acode, amount AS actual, 0 AS ddeals, 0 AS ufinish, '' AS ddomain, '' AS userbank,
'' AS deposituser, 0 AS ischk, 0 AS ano, 0 AS ppid, 0 AS optionid, '' AS cardnum, 0 AS agentid, '' AS platform, currency, brandid
FROM test_member_manual_adjust WHERE btype = 1234 AND uid = thisPlayer AND (currency = '' OR currency = 'CNY')
LIMIT 1)) x ORDER BY x.created desc limit 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
FETCH cur1 INTO a, b, c, d, e, f, g;
INSERT IGNORE INTO test_deposit_pool(dno,uid,dptype,amount,created,updated,status) VALUES(a, b, c, d, e, f, g);
CLOSE cur1;
END
i got updated rows = 0, what went wrong? The main select queries u do not have to check as it is cross checked already from my side to call individually and there are big amounts of data returned, in terms of logic, is there something im missing that causes updating empty rows? Thank youu
p,s: my function mainly is getting all players from LoopPlayerFirstDpt() , then at UpdateFirstDp(), for each player , get their data (1 row), and insert into the respective table.

SQL loop insert using declared table

I have a declared table which has a lot of data in it... I get the data by doing a select query on my InventoryLogs.. now, what I want is to insert this data on another table called MonthlySalesHistoryDetail... However I don't know how to get the values of my declared table...
this is a stored procedure:
Alter Procedure InsertMonthlySalesHistoryEndDate
#CurrentDate date,
#CreatedByID int,
#LastInsertID int
as
Declare #details table
(
RowID int identity(1,1) primary key,
MonthlySalesHistoryID int,
ItemID int,
MeasurementUnitID int,
QuantitySold numeric(18,4),
QuantityReturned numeric(18,4),
TotalSoldAmount numeric(18,4),
TotalReturnedAmount numeric(18,4)
)
Insert Into #details
(
MonthlySalesHistoryID,
ItemID,
MeasurementUnitID,
QuantitySold,
QuantityReturned,
TotalSoldAmount,
TotalReturnedAmount
)
SELECT
#LastInsertID,
il.ItemID,
il.MeasurementUnitID,
SUM(il.Quantity) as QuantitySold,
ISNULL((SELECT SUM(Quantity) FROM InventoryLogs WHERE TransactionType = 15 AND CAST(InventoryLogDate as date) = #CurrentDate),0) as QuantityReturned,
SUM(il.ComputedCost) as TotalSoldAmount,
ISNULL((SELECT SUM(ComputedCost) FROM InventoryLogs WHERE TransactionType = 15 AND CAST(InventoryLogDate as date) = #CurrentDate),0) as TotalReturnedAmount
FROM InventoryLogs il
WHERE il.TransactionType = 9 AND CAST(InventoryLogDate as date) = #CurrentDate
GROUP BY il.ItemID, il.MeasurementUnitID
declare #count int = (SELECT COUNT(*) FROM #details)
declare #counter int = 0
WHILE(#count > #counter)
BEGIN
SET #counter = #counter + 1
SELECT * FROM #details d Where d.RowID = #counter
INSERT INTO MonthlySalesHistoryDetails
(
MonthlySalesHistoryID,
ItemID,
MeasurementUnitID,
QuantitySold,
QuantityReturned,
TotalSoldAmount,
TotalReturnedAmount
)
VALUES
(
//I want to get the values of my
//SELECT * FROM #details d Where d.RowID = #counter here..
)
END
thanks in advance....
I didn't know that it was possible to do this insert... I thought it was only good for declared table
INSERT INTO MonthlySalesHistoryDetails
(
MonthlySalesHistoryID,
ItemID,
MeasurementUnitID,
QuantitySold,
QuantityReturned,
TotalSoldAmount,
TotalReturnedAmount
)
SELECT
d.MonthlySalesHistoryID,
d.ItemID,
d.MeasurementUnitID,
d.QuantitySold,
d.QuantityReturned,
d.TotalSoldAmount,
d.TotalReturnedAmount
FROM #details d Where d.RowID = #counter

Rewrite Stored Procedure

I have the next stored procedure which inserts values into 2 tables. To the 2nd table I insert id's of 2 last inserts from 1st table
However, I would like to rewrite it with one query instead of using temp table and while.
CREATE PROCEDURE CurrencyExhange
AS
DECLARE #TmpTable Table
(
ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
BillID int,
Amount decimal,
Rate decimal,
Date date
)
INSERT INTO #TmpTable
SELECT T.[BillID]
,[Amount]
,CR.Rate
,CR.Date
FROM [FinanceLabkovich].[dbo].[Transactions] T
JOIN [FinanceLabkovich].[dbo].Bills B ON B.BillID = T.BillID
JOIN [FinanceLabkovich].[dbo].Currencies C ON C.CurrencyID=B.CurrencyID
JOIN [FinanceLabkovich].[dbo].CurrencyRates CR ON CR.CurrencyRateID=FinanceLabkovich.dbo.GetRate(T.Date)
WHERE LOWER(C.Name)='usd' AND T.Income=1
ORDER BY T.Date
DECLARE #ToBillID int = (SELECT BillID FROM [FinanceLabkovich].[dbo].Bills B WHERE B.Name='Purse')
DECLARE #i int = (SELECT MIN(Id) FROM #TmpTable)
DECLARE #maxId int = (SELECT MAX(Id) FROM #TmpTable)
DECLARE #TransactionID int, #ToTransactionID int, #Amount decimal
DECLARE #date date
WHILE (#i<=#maxId)
BEGIN
SET #date = (SELECT Date FROM #TmpTable WHERE ID=#i)
SET #Amount = (SELECT AmountUSD FROM [FinanceLabkovich].[dbo].Cashflow WHERE Date=#date)
IF #Amount > 0
BEGIN
INSERT INTO [FinanceLabkovich].[dbo].[Transactions] (Name,BillID,ToBillID,Amount,Date,Income)
SELECT "Name"='Currency exhange'
,BillID
,#ToBillID
,#Amount
,T.Date
,"Income"=0
FROM #TmpTable T
WHERE ID=#i
SET #TransactionID = ##IDENTITY
INSERT INTO [FinanceLabkovich].[dbo].[Transactions] (Name,BillID,ToBillID,Amount,Date,Income)
SELECT "Name"='Currency exhange'
,#ToBillID
,BillID
,#Amount*Rate AS Total
,Date
,"Income"=1
FROM #TmpTable WHERE ID=#i
SET #ToTransactionID = ##IDENTITY
INSERT INTO [FinanceLabkovich].[dbo].[Transfers]
SELECT #TransactionID, #ToTransactionID
END
SET #i += 1
END
Any help appreciated.

case statement in where clause - SQL Server 2008

SELECT
PDADate, T.Merchandizer_ID, T.Merchandizer, Merchandizer_LoginName,
STORE_ID, STORE_CODE, STORE_NAME,
ACCOUNT_ID, ACCOUNT_NAME, Account_Store_Format_Id, Account_Store_Format,
StoreType_Id, StoreType, T.Listid, T.Listname,
T.TimeIn, T.TimeOut, T.PlannedDate, T.Reason, TaskCode, TotalTime
FROM
[dbo].Report_RD_Coverage T
INNER JOIN
#TempLocationH TL ON TL.LocationId=T.Location_Id
WHERE
CONVERT(Date, PDADate) Between (#Start_Date) AND Isnull(#End_Date, #CurrentDate)
AND T.Account_Id IN
(SELECT
CASE WHEN #Account_Id IS NULL THEN T.Account_Id
ELSE (SELECT * FROM UDF_SplitString(#Account_Id,','))
END
)
AND T.StoreType_Id IN
(SELECT
CASE WHEN #StoreType_Id IS NULL THEN T.StoreType_Id
ELSE (SELECT * FROM UDF_SplitString(#StoreType_Id,','))
END
)
AND T.Store_Id IN
(SELECT
CASE WHEN #Store_Id IS NULL THEN T.Store_Id
ELSE (SELECT * FROM UDF_SplitString(#Store_Id,','))
END
)
If #Account_Id, #StoreType_Id and #Store_Id are null the it should select all the ACCOUNT_ID, STORETYPE_ID and STORE_ID otherwise based on parameter value it should filter.
UDF_SplitString is the function to split up comma-separated strings, and its return value is a table like:
- 1
- 2
- 3
I'm getting this error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
CASE must return a scalar value, so try this variation instead:
select PDADate, T.Merchandizer_ID, T.Merchandizer, Merchandizer_LoginName, STORE_ID, STORE_CODE,
STORE_NAME, ACCOUNT_ID, ACCOUNT_NAME, Account_Store_Format_Id, Account_Store_Format,
StoreType_Id, StoreType, T.Listid, T.Listname, T.TimeIn, T.TimeOut, T.PlannedDate,
T.Reason, TaskCode, TotalTime
from [dbo].Report_RD_Coverage T
inner join #TempLocationH TL on TL.LocationId = T.Location_Id
where CONVERT(date, PDADate) between (#Start_Date)
and Isnull(#End_Date, #CurrentDate)
and (
#Account_Id is null
or T.Account_Id in (
select *
from UDF_SplitString(#Account_Id, ',')
)
)
and (
#StoreType_Id is null
or T.StoreType_Id in (
select *
from UDF_SplitString(#StoreType_Id, ',')
)
)
and (
#Store_Id is null
or T.Store_Id in (
select *
from UDF_SplitString(#Store_Id, ',')
) end
)
I tried this and reached very closer but you have to do something from what I found a link.
This is my try. the only thing you need to build is the #udf data.
declare #Store_Id INT;
declare #Account_Id INT;
DECLARE #UDF[9] OF VARCHAR(30);
set #Store_Id = 99 --NULL
set #Account_Id = 15
SET #UDF = '11,12,13,14,15,16'
SELECT #Account_Id AS ACID
WHERE CAST(#Account_Id AS VARCHAR(6)) IN (
CASE WHEN #Store_Id IS NULL THEN CAST(#Account_Id AS VARCHAR(6))
ELSE #UDF END
The link is at
http://www.codeproject.com/Questions/473174/CreateplusArrayplusinplusSqlplusServer
DECLARE #INSTR as VARCHAR(MAX)
SET #INSTR = '2,3,177,'
DECLARE #SEPERATOR as VARCHAR(1)
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
SET #SEPERATOR = ','
CREATE TABLE #tempTab (id int not null)
WHILE PATINDEX('%' + #SEPERATOR + '%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%' + #SEPERATOR + '%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #tempTab (id) VALUES (#VALUE)
END
SELECT * FROM myTable WHERE id IN **(SELECT id FROM #tempTab)**
DROP TABLE #tempTab
you can extract for the sql in bold and the logic how to create temp table and its data and I hope you will get what you want.
> This is the my right solultion........now its working correctly
CREATE TABLE #Store_Id (StoreID varchar(20))
IF #Store_Id != '0'
BEGIN
INSERT INTO #Store_Id
SELECT data FROM UDF_SplitString(#Store_Id,',')
END
ELSE
BEGIN
INSERT INTO #Store_Id
SELECT '0'
END
CREATE TABLE #StoreType_Id (StoreTypeID varchar(20))
IF #StoreType_Id != '0'
BEGIN
INSERT INTO #StoreType_Id
SELECT data FROM UDF_SplitString(#StoreType_Id,',')
END
ELSE
BEGIN
INSERT INTO #StoreType_Id
SELECT '0'
END
CREATE TABLE #Account_Id (AccountID varchar(20))
IF #Account_Id != '0'
BEGIN
INSERT INTO #Account_Id
SELECT data FROM UDF_SplitString(#Account_Id,',')
END
ELSE
BEGIN
INSERT INTO #Account_Id
SELECT '0'
END
INSERT INTO #FinalTable(VisitDate,Merchandizer_Id,Merchandizer,MerchandizerLogin,StoreId,StoreCode,StoreName,AccountId,AccountName,
Account_Store_Format_Id,Account_Store_Format,StoreTypeId ,StoreType ,ListId ,ListName,TimeIn ,TimeOut,PlannedDate ,Reason ,TaskCode,TotalTime)
SELECT Visit_Date,T.Merchandizer_ID,T.Merchandizer,Merchandizer_LoginName,STORE_ID,STORE_CODE,STORE_NAME,ACCOUNT_ID,ACCOUNT_NAME,
Account_Store_Format_Id,Account_Store_Format,StoreType_Id,
StoreType,T.Listid,T.Listname,T.TimeIn,T.TimeOut,T.PlannedDate,T.Reason,TaskCode,TotalTime
FROM [dbo].Report_RD_Coverage T
INNER JOIN #TempLocationH TL ON TL.LocationId=T.Location_Id
INNER JOIN #Store_Id on CONVERT(VARCHAR,t.Store_Id) = CASE WHEN #Store_Id = '0' THEN convert(VARCHAR,t.Store_Id) ELSE StoreID END
INNER JOIN #StoreType_Id on CONVERT(VARCHAR,t.StoreType_Id) = CASE WHEN #StoreType_Id = '0' THEN convert(VARCHAR,t.StoreType_Id) ELSE StoreTypeID END
INNER JOIN #Account_Id on CONVERT(VARCHAR,t.Account_Id) = CASE WHEN #Account_Id = '0' THEN convert(VARCHAR,t.Account_Id) ELSE AccountID END
WHERE CONVERT(Date,PDADate) Between #Start_Date AND #End_Date

Create LOG for tables in SQL Server

I have a table Sample and another SampleLog
With these structure I want to write codes to log. You can see my codes after structures of tables
CREATE TABLE [dbo].[Sample](
[ID] [int] NULL,
[Name] [varchar](10) NULL
)
CREATE TABLE [dbo].[SampleLog](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Date] [datetime] NULL,
[UserName] [varchar](100) NULL,
[Type] [char](1) NULL
)
I have written this code but it doesn't work for Delete and Update .
CREATE TRIGGER SampleTrigger ON Sample
AFTER INSERT, UPDATE, DELETE
AS
DECLARE
#ID int ,
#Name varchar(10),
#Date datetime,
#UserName VARCHAR(128) ,
#Type CHAR(1) ,
#sql nvarchar(500)
SELECT
#UserName = SYSTEM_USER ,
#Date = CONVERT(VARCHAR(8), GETDATE(), 112)
+ ' ' + CONVERT(VARCHAR(12), GETDATE(), 114)
IF EXISTS (SELECT * FROM inserted)
BEGIN
IF EXISTS (SELECT * FROM deleted)
BEGIN
SELECT #Type = 'U'
select #ID = ID from deleted
select #Name = Name from deleted
END
ELSE
BEGIN
SELECT #Type = 'I'
select #ID = ID from inserted
select #Name = Name from inserted
END
END
ELSE
BEGIN
SELECT #Type = 'D'
select #ID = ID from deleted
select #Name = Name from deleted
END
insert into SampleLog(ID, Name, Date, UserName, Type)
values(#ID, #Name, #Date, #UserName, #Type)
SQL Server gives me this error
The row values updateed or deleted either do not make the row unique or they alter multiple rows(2 rows)
You've coded for single row updates and deletes. Think sets!
CREATE TRIGGER SampleTrigger ON Sample after INSERT, UPDATE, DELETE
AS
SET NOCOUNT ON;
insert into SampleLog
(ID,Name,Date,UserName,Type)
SELECT
D.ID, D.NAME, GETDATE(), SYSTEM_USER,
CASE WHEN I.ID IS NULL THEN 'D' ELSE 'U' END
FROM
DELETED D
LEFT JOIN
INSERTED I ON D.ID = I.ID
UNION ALL
SELECT
I.ID, I.NAME, GETDATE(), SYSTEM_USER, 'I'
FROM
INSERTED I
LEFT JOIN
DELETED D ON D.ID = I.ID
WHERE
D.ID IS NULL
GO