duplicating 3 lines in sql server but changing the Period id - c#

On my web app in visual studio web forms I am creating, it is pushing and pulling data from a SQL Server database. I need help with a problem i have run into. On the rates page, is a gridview that displays the rates for the current period, there are 6 columns in total.
I need to put a button that would when clicked copy/duplicate the last 3 lines being Period_Id, Description, Rate1, Rate2, Rate3, Rate4 . The problem is the period Id, for every 3 lines it is assigned 1 Id IE.
Period_Id, Description, Rate1,Rate2,Rate3,Rate4
1 , Example , 7 , 6 , 7 , 0
1 , Example ,8 , 4 ,1 , 100
1 , Example ,8 , 4 ,1 , 400
When the lines are copied the Period_Id Must change but follow the sequence of 1,1,1 and become 2,2,2 when copied again become 3,3,3 and keep the other data associated to it.

First of all, you should have a Primary Key defined for the table.
Secondly, you can do this by following these steps.
Create a Stored Proc in SQL Server DB
Call the below Stored Proc from your Application.
`
Create Procedure CopyRates
#PeriodID INT
AS
BEGIN
//Populate a temp table with all the values you want to copy from <YOURTABLE>
CREATE TABLE #TestData (Period_Id int, Description varchar(10), Rate1 int, Rate2 int, Rate3 int, Rate4 int)
INSERT INTO #TestData (Period_Id, Description, Rate1, Rate2, Rate3, Rate4)
VALUES
(Select PeriodID, Descriptiom Rate1, Rate2, Rate3, Rate4)
From <YOURTABLE>
Where PeriodID = #PeriodID
)
INSERT INTO <YOURTABLE> (Period_Id, Description, Rate1, Rate2, Rate3, Rate4)
SELECT Period_Id +1, Description,Rate1, Rate2, Rate3, Rate4
FROM #TestData
END

If you're just wanting to insert this data into the table with just period_id being changed you can do a simple insert into with a select.
Sample Data;
CREATE TABLE #TestData (Period_Id int, Description varchar(10), Rate1 int, Rate2 int, Rate3 int, Rate4 int)
INSERT INTO #TestData (Period_Id, Description, Rate1, Rate2, Rate3, Rate4)
VALUES
(1,'Example',7,6,7,0)
,(1,'Example',8,4,1,100)
,(1,'Example',8,4,1,400)
Your insert statement would be something like this;
INSERT INTO #TestData (Period_Id, Description, Rate1, Rate2, Rate3, Rate4)
SELECT Period_Id +1
,Description
,Rate1
,Rate2
,Rate3
,Rate4
FROM #TestData
And your results will look like this;
Period_Id Description Rate1 Rate2 Rate3 Rate4
1 Example 7 6 7 0
1 Example 8 4 1 100
1 Example 8 4 1 400
2 Example 7 6 7 0
2 Example 8 4 1 100
2 Example 8 4 1 400

Related

Custom Autogenerated Column in SQL Server

I want to generate a unique PrescriptionNo for each of the Prescription based on the shopid.
I have tried the following way
id PrescriptionNo Shopid Amount
1 PRES001 2 100
2 PRES002 2 200
3 PRES001 1 100
4 PRES003 2 200
select top 1 'PRES' + right('000' + CAST(ROW_NUMBER() over (order by id) + 1 AS VARCHAR(3)),3)
from prescription
where shopid = 2
order by id desc
Try this:
create table #tmp1 (id int, prescriptionno varchar(10), shopid int, amount int);
insert into #tmp1 values (1,'PRES001',2,100);
insert into #tmp1 values (2,'PRES002',2,200);
insert into #tmp1 values (3,'PRES001',1,100);
insert into #tmp1 values (4,'PRES003',2,200);
select 'PRES' + RIGHT(concat('000',ISNULL(max(right(prescriptionNo,3)),0)+1),3)
from #tmp1
where shopid = 3
=> Returns 'PRES0001'
select 'PRES' + RIGHT(concat('000',ISNULL(max(right(prescriptionNo,3)),0)+1),3)
from #tmp1
where shopid = 2
==> Returns 'PRES0004'
By using just max() allows you to use ISNULL(..,0).

MSSQL update multiple records all at once by one stored procedure

I have a stored procedure that currently looks like this:
create procedure zsp_updateTyp5Graph
(
#DayList nvarchar(1000),
#Sales int,
#SearchedUserId int
)
as
update SearchedUserGraphData
set SalesForDay=#Sales
where Day in (SELECT * FROM dbo.SplitString(#DayList)) and SearchedUserId=#SearchedUserId
The daylist parameter looks like following:
0,1,2,3,4,5,6
I have in my SearchedUserGraphData table two columns and 7 records(7 days) that should be updated. For example:
Day Sales
0 5
1 6
2 4
3 3
4 7
5 9
6 11
I have "partially" solved this by passing list of days... But I'm unable to find out how can I pair up this #DayList parameter with sales data...
I have a SplitString function that I've created and looks like this for matching the records in DB:
ALTER FUNCTION [dbo].[splitstring] ( #stringToSplit VARCHAR(MAX) )
RETURNS
#returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
Now the issue is that I need to somehow pass from my C# application combined list of Days and their corresponding sales, and then update the records all at once, without calling the procedure 7 times to update 7 records (that would be catastrophical from performance standpoint in my eyes)...
Can someone help me out with this?
P.S. Guys, the "best" idea that I get on this one is:
The daylist parameter looks like following:
0,1,2,3,4,5,6
And then sales:
11,22,44,55,66,77,88
This is the way I can pass the sales and days parameters... But then what? I cannot know what sale corresponds to which day...
I could form a key-value pair dictionary string in my C# application maybe like:
{ Day: 1 Sales: 44, Day: 2 Sales: 55 }
this is how I could form the string.. But then I need to break down this string in MSSQL to match => day 1 => update with sales 44 ...
You can create a SalesPerDay type
CREATE TYPE [dbo].[SalesPerDay] AS TABLE (
day INT NOT NULL,
sales INT NOT NULL
);
Then, your proc would look like this
create procedure zsp_updateTyp5Graph
(
#DayList SalesPerDay READONLY,
#SearchedUserId int
)
as
update SearchedUserGraphData
set SalesForDay=dayList.sales
FROM SearchedUserGraphData baseTable
INNER JOIN #DayList dayList ON dayList.day = baseTable.day
WHERE SearchedUserId=#SearchedUserId
And from the C#, you can build a DataTable and send it to the proc.
var table = new DataTable();
table.Columns.Add("day", typeof(int));
table.Columns.Add("sales", typeof(int));
//Add data
table.Rows.Add(new []{1, 200});
table.Rows.Add(new []{2, 200});
//More code
Command.Parameters.AddWithValue("#DayList", table);

How can I set the value of column equals (column1 * column2)

I'm new to SQL Server Management Studio, let's say I have 3 columns in my tbl_product, column1 (nchar(60)), column2 (nchar(60)), and in my column3 I want its value to be the result of (column1 * column2), how can I do that?
I saw a "Formula" in the column properties, but I'm not sure how to set a formula there, here is the screenshot:
Note: let's just set the column1 & column2's datatype to nchar.
Presuming both columns are strings that represent decimals set your Formula to this:
CONVERT(decimal,column1) * CONVERT(decimal,column2)
To change how the column is displayed simply change your SELECT statements. The column data will always be "stored" as accurate as possible.
Try running this:
SELECT CAST(column3 as decimal(10,2)) As ComputedColumn FROM tbl_product
In the above statement the cast means "show me 10 digits in total, and 2 digits after the decimal point". You can change those numbers to whatever you'd like.
You can sum two columns using transact sql while defining your table.
CREATE TABLE dbo.Products
(
ProductID int IDENTITY (1,1) NOT NULL
, QtyAvailable smallint
, UnitPrice money
, InventoryValue AS QtyAvailable * UnitPrice
);
-- Insert values into the table.
INSERT INTO dbo.Products (QtyAvailable, UnitPrice)
VALUES (25, 2.00), (10, 1.5);
-- Display the rows in the table.
SELECT ProductID, QtyAvailable, UnitPrice, InventoryValue
FROM dbo.Products;
Microsoft Docs link for Specify Computed Columns in a Table
CREATE TABLE [dbo].[Test]
( [Test1] [nchar(10)] NULL,
[Test2] [nchar(10)] NULL,
[Total] AS (cast ([a] as int)+ cast( [b] as int))
) ON [PRIMARY]
GO
INSERT INTO dbo.Test ( test1, test2 ) VALUES
( '1', -- test1 - int
'2' -- test2 - int
)
SELECT * FROM dbo.Test
Results:
Test1 test2 total
1 2 3

Calling procedure from multi user

I have come up with scenario and i am really struggling with it. Please help me in this. i have table below and store procedure is calling for this table on button click in c# and data source is assign to grid.
Id Product QtyReceive QtyDispatch Location
1 HP2030 20 0 A
Below is procedure which is call on click event and it just select the require quantity of product which we require from specific location.
DECLARE #Data TABLE
(
Id int identity(1,1)
, Product varchar(10)
, QtyReceive int
, QTYDispatch int
, Location varchar(10)
)
DECLARE #Qty int = 10
INSERT #Data VALUES
('HP2030', 20 ,5,'A');
WITH sumqty AS
(
SELECT *, SUM(QtyReceive -QTYDispatch) OVER (PARTITION BY Product ORDER BY Id) AS TotalQty FROM #Data
)
,takeqty AS (
SELECT *,
CASE
WHEN #Qty >= TotalQty THEN QtyReceive
ELSE #Qty - ISNULL(LAG(TotalQty) OVER (PARTITION BY Product ORDER BY Id), 0)
END AS TakeQty
FROM sumqty
)
SELECT
Product
, TotalQty
, TakeQty
, Location
FROM takeqty WHERE TakeQty > 0
ORDER BY Location;
Now there is a problem let say two user sitting at two different computer and User 1 required 10 quantity and other user required 5 quantity. They click button to get quantity at same time and save it at same time and dispatch quantity update with quantity 10 instead of 10+5=15. It happens when both user hit save at same time. No of user can be vary. Is there any solution to this problem?
I try to understand the whole scenario.

I want to search in SQL Server with must have parameter in one colunm

I am using c# and SQL Server 2008.
I have table like this
id | propertyTypeId | FinishingQualityId | title | Description | features
1 1 2 prop1 propDEsc1 1,3,5,7
2 2 3 prop2 propDEsc2 1,3
3 6 5 prop3 propDEsc3 1
4 5 4 prop4 propDEsc4 3,5
5 4 6 prop5 propDEsc5 5,7
6 4 6 prop6 propDEsc6
and here is my stored code (search in the same table)
create stored procdures propertySearch
as
#Id int = null,
#pageSize float ,
#pageIndex int,
#totalpageCount int output,
#title nvarchar(150) =null ,
#propertyTypeid int = null ,
#finishingqualityid int = null ,
#features nvarchar(max) = null , -- this parameter send like 1,3 ( for example)
begin
select
row_number () as TempId over( order by id) ,
id, title, description,
propertyTypeId, propertyType.name,
finishingQualityId, finishingQuality.Name,
freatures
into #TempTable from property
join propertyType on propertyType.id= property.propertyTypeId
join finishingQuality on finishingQuality.id = property.finishingQualityId
where
property.id = isnull(#id,property.id ) and proprty.PropertyTypeId= isnull(#propertyTypeid,property.propertyTypeId)
select totalpageconunt = ((select count(*) from #TempTable )/#pageSize )
select * from #TempTable where tempid between (#pageindex-1)*#pagesize +1 and (#pageindex*#pageSize)
end
go
I can't here filter the table by feature I sent. This table has too many rows I want to add to this stored code to filter data for example when I send 1,3 in features parameter I want to return row number one and two in the example table I write in this post (want to get the data from table must have the feature I send)
Many thanks for every one helped me and will help
Sending a delimited list of values to match with a delimited value in a column will generally get you into trouble as the only way to do it is to split each value out from the string. (Also why indexing them is pointless)
You should create an additional table containing the id from your property table & a row for each feature;
property_id feature
----------- -------
5 5
5 7
Then matching is much simpler. You can send the procedure the list of features you want to match ideally using a table valued parameter or alternatively a table function.

Categories

Resources