How to insert Serial Number to Unpivoted Column - c#

I have a table in my DB which contains Date and Time separately in columns for a Time Table so for Displaying it as a Single one in the front end I had joined Date and Time Column and Inserted into Temporary table and Unpivoted it,but the Pk_id is same for both the Unpivoted Columns so in the Front end in the Drop down box when I select the item in the Index say at 6 in DDL after a postback occur it will return to Index 1 in DDL.So,is there a way to put Serial number for the Unpivoted columns, My Unpivot Query is,
Select * from
(
Select pk_bid,No_of_batches,Batch1,Batch2,Batch3,Batch4, from #tempbatch
) as p
Unpivot(Batchname for [Batches] in([Batch1],[Batch2],[Batch3],[Batch4])) as UnPvt
In the above query pk_bid & No_of_Batches is same so If I put Rownumber() Partition by pk_bid Order by pk_bid or Rownumber() Partition by No_of_Batches Order by No_of_Batches it gives the 1,1 only as it is same.

I had solved My above Problem like this,
I had created another Temporary table and created Serial Number with the column in that table with differant values the Query I had done is,
Create Table #Tempbatch2
(
pk_bid int,
No_of_batches int,
Batchname Varchar(max),
[Batches] Varchar(max)
)
Insert Into #Tempbatch2
Select * from
(
Select pk_batchid,No_of_batches,Batch1,Batch2,Batch3,Batch4 from #tempbatch
) as p
Unpivot(Batchname for [Batches] in([Batch1],[Batch2],[Batch3],[Batch4])) as UnPvt
Select Row_number() OVER(ORDER BY (Batchaname)) as S_No,pk_bid,No_of_batches,Batchname,[Batches] from #Tempbatch2

Related

SQL Server allow duplicates in any column, but not all columns

I've searched through numerous threads to try to find an answer to this but any answer I've found suggests using a unique constraint on a single column, or multiple columns.
My problem is, I'm writing an application in C# with a SQL Server back end. One of the features is to allow a user to import a .CSV file into the database after a little bit of pre-processing. I need to find the quickest method to prevent the user from importing the same data more than once. The data will look something like
ID -- will be auto-generated in SQL Server (PK)
Date Time(datetime)
Machine(nchar)
...
...
...
Name(nchar)
Age(int)
I want to allow any number of the columns to be duplicate values, a long as the entire record is not.
I was thinking of creating another column in the database, obtained by hashing all of the columns together and making it unique but want sure if that was the most efficient method, or if the resulting hash would be guaranteed unique. The CSV files will only be around 60 MB, but there will be tens of thousands of them.
Any help would be appreciated.
Thanks
You should be able to resolve this by creating a unique constraint which includes all the columns.
create table #a (col1 varchar(10), col2 varchar(10))
ALTER TABLE #a
ADD CONSTRAINT UQ UNIQUE NONCLUSTERED
(col1, col2)
-- Works, duplicate entries in columns
insert into #a (col1, col2)
values ('a', 'b')
,('a', 'c')
,('b', 'c')
-- Fails, full duplicate record:
insert into #a (col1, col2)
values ('a1', 'b1')
,('a1', 'b1')
The code below can work to ensure that you don't duplicate the [Date Time], Machine, [Name] and Age columns when you insert the data.
It's important to ensure that at the time of running the code, each row of the incoming dataset has a unique ID on it. This code just fails to shift any rows where the ID gets selected because all four other values are already duplicated in the destination table.
INSERT INTO MAIN_TABLE ([Date Time],Machine,[Name],Age)
SELECT [Date Time],Machine,[Name],Age
FROM IMPORT_TABLE WHERE ID NOT IN
(
SELECT I.ID FROM IMPORT_TABLE I INNER JOIN MAIN_TABLE M
ON I.[Date Time]=M.[Date Time]
AND I.Machine=M.Machine
AND I.[Name]=M.[Name]
AND I.Age=M.Age
)

Create columns with a loop

I have an MVC project and in the Database I want to create a table with one column and more columns in a loop to the count of a List defined somewhere in my solution. How to achieve this?
CREATE TABLE [dbo].[Table]
(
[Id] INT NOT NULL PRIMARY KEY,
[tag] NVARCHAR(MAX) NOT NULL
while... <something becomes MyList.Count>
[value] NVARCHAR(MAX)
)
I guess you have write a separate query for that looping after creation, which would be an ALTER TABLE.
Like,
WHILE(condition)
BEGIN
ALTER TABLE Table1 ADD column_name datatype
END
Here, the condition should be the count. The column name depends on how you pass the values. I would pass them as XML data in table format, then convert it to a table in SQL and then loop through them while altering.
Like,
WHILE((SELECT COUNT(id) FROM temp))
BEGIN
EXECUTE('ALTER TABLE Table1 ADD COLUMN '+(SELECT TOP 1 column_name FROM temp)+' NVARCHAR(MAX)')
DELETE FROM temp WHERE temp.id = (SELECT TOP 1 id FROM temp)
END
Hope this works :)

SQL Server : randomize rows (shuffle IDs)

Is there a way to randomize the rows in SQL Server?
I don't want to retrieve the rows in a random manner, I know how to to that.
I want to shuffle the row IDs in the database (ex. ID1 will change to ID27 and ID27 will change to ID1).
I can copy all records to a temporary table, truncate the original table and insert the records back from the temporary table using a parallel loop for randomization.
Is there an easier way to this ?
ID is the identity seed, auto incremented
This sounds like a really strange requirement. Since the id is an identity you can't change that, so you'll have to swap all the other data on the row, which you could probably do with something like this:
select
a.id as old_id,
b.*
into #newdata
from
(
select
id,
row_number() over (order by id) as rn
from
data
) a
join (
select
*,
row_number() over (order by newid()) as rn
from
data
) b on a.rn = b.rn
This creates a temp table with old and new id numbers + all the columns from the table. You could then use to update all the columns for the rows from in the original table using this temp. table.
Can't really recommend doing this, especially if there's a lot of rows. Before doing this you probably should take a table level exclusive lock to the table just in case.

SQL query to insert FIRST row on a table

I have a SQL table with 10 columns, and two of the columns are project and employee.
What I am attempting to do is I have a drop down list of values for
the employee field in this table,
And I need to do an INSERT statement into the same table, inserting
all of the values that exist in the table, and just change the value
of the employee field on inserting.
I only want to insert a single record, so I am fearing that if I
execute an insert statement with on a WHERE project equals what the
user selected, that I will get thousands of rows inserted.
I just want to insert one single row from the table where the project
field is equal to what the user selected in a drop down, and insert
one single row copying all the data of a single row of that project,
and
Just replace the employee field with what the user selected in a
drop down.
You can INSERT using SELECT TOP 1 to get a row from the existing table with a WHERE clause that includes the required Project, like so:
DECLARE #EmployeeIdToAdd int = 12345
DECLARE #ProjectId int = 10
INSERT INTO [ProjectEmployees] (Col1, Col2,..., Project, Employee)
SELECT TOP 1 Col1, Col2,..., Project, #EmployeeIdToAdd
FROM ProjectEmployees
WHERE Project = #ProjectId
You would just need to set the parameters accordingly.

Select unique random rows from SQL Server table but always duplicates

i am not the best with sql but i try my best to get my Problems done. I have a table "just" which is filled with Columns ( ID (PK, Identity), Char, Serv , Random ) . Now i want to select a random row from this table and insert it into the Table "f_WinGet". So far all my Procedures take this Step fine , but i always get Duplicates in the second table.
First table : 84 rows
Second table: needed 35 random out of 84.
I have tried many other ways but i always get the same result. All my Procedure for random are binded to a Button i a C# Programm. All is working fine so far , but i always have some Duplicates of Rows in my Table.
INSERT INTO f_TWinGet
SELECT TOP 1 Percent Char, Serv, Random
FROM ( select distinct Char, Serv, Random from dbo.just) as derived1
ORDER BY CHECKSUM(NEWID())
It would be nice , if anyone hase an Idea how i can fix my Problem. I am still trying , but all what i get are always the same result.
It you want to insert 35 rows, do it all at once:
INSERT INTO f_TWinGet(char, serv, random)
SELECT TOP 35 Char, Serv, Random
FROM (select distinct Char, Serv, Random
from dbo.just
) derived1
ORDER BY CHECKSUM(NEWID());
If you really want to do them one at a time, I would suggest using not exists:
INSERT INTO f_TWinGet(char, serv, random)
SELECT TOP 1 Char, Serv, Random
FROM (select distinct Char, Serv, Random
from dbo.just
) d
WHERE not exists (select 1 from f_TWinGet f where t.char = f.char and t.serv = f.serv and t.random = f.random)
ORDER BY CHECKSUM(NEWID());
Note that char is a reserved word, so it should be in square braces. I am leaving the names you have have them in your query.
With a table as small as yours you can use something like:
INSERT INTO f_TWinGet
SELECT TOP 1 j.Char, j.Serv, j.Random
FROM dbo.just j
LEFT JOIN f_TWinGet f
ON f.Char = j.Char
AND j.Serv = f.Serv
AND j.Random = f.Random
WHERE f.Char IS NULL
ORDER BY NEWID()
This way making sure that the values you're trying to insert is not on the final table.

Categories

Resources