Insert into SQL table using Loop - sql-server

I have two tables
Chapters_tbl (chID, name)
Status_tbl (chID, Ch_status)
For every chID in Chapters_tbl, I want to insert that chID into Status_tbl and Ch_status
I can use both a SQL Server stored procedure or Entity Framework in C#.
How can I do this?

Using T-SQL...
INSERT dbo.Status_tbl (chID, Ch_status)
SELECT
c.chID,
Ch_status = 1
FROM
dbo.Chapters c
WHERE
NOT EXISTS (
SELECT 1
FROM dbo.Staus_tbl s
WHERE c.chID = s.chID
);

Related

Merge..USING..WHEN SQL Server equivalent in PostgreSQL

Right now, we are trying to migrate a stored procedure from SQL Server to PostgreSQL. In this, We saw a querying method MERGE..USING..WHEN. So I couldn't find the equivalent. So is there any option to replicate this functionality? The actual query is given below.
WITH phase_list AS (
SELECT #id_plant AS id_plant
, id_phase
, date_started
FROM OPENJSON(#phase_list)
WITH (
id_phase INT '$.id_phase',
date_started DATE '$.date_started'
)
WHERE date_started IS NOT NULL
)
MERGE grow.plant_phase AS t
USING phase_list AS s
ON s.id_plant = t.id_plant AND s.id_phase = t.id_phase
WHEN MATCHED AND (t.date_started <> s.date_started) THEN
UPDATE
SET t.date_started=s.date_started,
t.date_updated=getutcdate(),
t.updated_by=#id_user
WHEN NOT MATCHED BY TARGET THEN
INSERT (id_plant, id_phase, date_started, created_by, updated_by)
VALUES (s.id_plant, s.id_phase, s.date_started, #id_user, #id_user)
WHEN NOT MATCHED BY SOURCE AND t.id_plant = #id_plant THEN
DELETE;
Can we replicate the same using any join operation with some if/else conditions? or any other approach?

Encrypting data on PostgreSQL

I'm running some queries using PostgreSQL for student purposes. Now I need to encrypt some fields using AES256 to run the same queries and compare the times. Any idea how this can be done using UPDATE table? For example, I need to encrypt the customer address of the table address. Can I do this using UPDATE? Can anyone give me an example? Couldn't find anything online. Thanks.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
INSERT INTO table(name,age) VALUES(
PGP_SYM_ENCRYPT('John', 'AES_KEY'),
PGP_SYM_ENCRYPT('22', 'AES_KEY')
);
UPDATE table SET
(name,age) = (
PGP_SYM_ENCRYPT('Jona', 'AES_KEY'),
PGP_SYM_ENCRYPT('15','AES_KEY')
) WHERE id='1';
SELECT
PGP_SYM_DECRYPT(name::bytea, 'AES_KEY') as name
PGP_SYM_DECRYPT(age::bytea, 'AES_KEY') as age
FROM table WHERE(
LOWER(PGP_SYM_DECRYPT(name::bytea, 'AES_KEY')
LIKE LOWER('%John%')
);

Convert multiple SQL Server queries into one

I have a page that ask of users opinion about a topic. Their responses are then saved into a table. What I want to do is to check how many users selected an option 1,2,3 and 4.
What I have now are multiple T-SQL queries that run successfully but I believe there is a simplified version of the code I have written. I would be grateful if someone can simplify my queries into one single query. Thank you.
here is sample of data in the database table
enter image description here
$sql4 = "SELECT COUNT(CO) FROM GnAppItms WHERE CO='1' AND MountID='".$mountID."'";
$stmt4 = sqlsrv_query($conn2, $sql4);
$row4 = sqlsrv_fetch_array($stmt4);
$sql5="SELECT COUNT(CO) FROM GnAppItms WHERE CO='2' AND MountID='".$mountID."'";
$stmt5=sqlsrv_query($conn2,$sql5);
$row5=sqlsrv_fetch_array($stmt5);
$sql6="SELECT COUNT(CO) FROM GnAppItms WHERE CO='3' AND MountID='".$mountID."'";
$stmt6=sqlsrv_query($conn2,$sql6);
$row6=sqlsrv_fetch_array($stmt6);
$sql7="SELECT COUNT(CO) FROM GnAppItms WHERE CO='4' AND MountID='".$mountID."'";
$stmt7=sqlsrv_query($conn2,$sql7);
$row7=sqlsrv_fetch_array($stmt7);
You can do it by using group by in sql server
example :
create table a
(id int,
mountid nvarchar(100),
co int,
)
insert into a values (1,'aa',1)
insert into a values (2,'aa',2)
insert into a values (3,'aa',1)
insert into a values (4,'aa',2)
insert into a values (5,'aa',3)
Query
select co,count(co)as countofco from a
where mountid='aa'
group by
co
result
co countofco
1 2
2 2
3 1
Note : Beware of SQL injection when you are writing a sql query, so always use parametrized query. You can edit the above example code and make it as a parametrized query for preventing sql injection

Check for duplicate records in sql database using vb.net

Assuming my table consist of two columns ID and Name.
And assume I have my stored procedure working on vb.net that inserts rows into the database.
But my system needs to check if an ID entered in a textbox already exists in the database when ADD button is click.
CREATE PROCEDURE AddOfficeEquipmentProfile
(
#OE_ID varchar(11),
#OE_Category char(3) =NULL,
#OE_SubCategory char(3)= NULL,
#OE_Name varchar(35)=NULL,
#OE_User varchar(35)=NULL,
#OE_Brand varchar(15)=NULL,
#OE_Model varchar(35)=NULL,
#OE_Specs varchar(1000)=NULL,
#OE_SerialNo varchar(35)=NULL,
#OE_PropertyNo varchar(35)=NULL,
#OE_MacAddress varchar(100)=NULL,
#OE_Static_IP varchar(15)=NULL,
#OE_Vendor varchar(35)=NULL,
#OE_PurchaseDate smalldatetime,
#OE_WarrantyInclusiveYear int=NULL,
#OE_WarrantyStatus char(2)= NULL,
#OE_Status varchar(15)=NULL,
#OE_Dept_Code char(3)= NULL,
#OE_Location_Code char(8)= NULL,
#OE_Remarks varchar(1000)= NULL
)
AS
INSERT INTO tblOfficeEquipmentProfile (OE_ID, OE_Category, OE_SubCategory, OE_Name, OE_User, OE_Brand, OE_Model, OE_Specs, OE_SerialNo,
OE_PropertyNo, OE_MacAddress, OE_Static_IP, OE_Vendor, OE_PurchaseDate, OE_WarrantyInclusiveYear, OE_WarrantyStatus, OE_Status, OE_Dept_Code,
OE_Location_Code, OE_Remarks )
VALUES (#OE_ID, #OE_Category, #OE_SubCategory, #OE_Name, #OE_User, #OE_Brand, #OE_Model,
#OE_Specs, #OE_SerialNo, #OE_PropertyNo, #OE_MacAddress, #OE_Static_IP, #OE_Vendor, #OE_PurchaseDate, #OE_WarrantyInclusiveYear, #OE_WarrantyStatus,
#OE_Status, #OE_Dept_Code, #OE_Location_Code, #OE_Remarks)
GO
few things you can do
make ID column as primary key, when insert you will get exception if duplicated
You can use auto increment ID, then you don't need to check ID exit or not. database will handle that
If you can't do above, run select statement or stored procedure to check whether id exist or not.
If this is for SQL Server and you're using a stored procedure - just try something like this:
CREATE PROCEDURE AddOfficeEquipmentProfile
(
#OE_ID varchar(11),
..... all your other parameters here.....
)
AS
IF NOT EXISTS (SELECT * FROM dbo.tblOfficeEquipmentProfile WHERE OE_ID = #OE_ID)
INSERT INTO dbo.tblOfficeEquipmentProfile(.... list of columns.....)
VALUES (......list of values................)
Assuming that OE_ID is your primary key and will be unique. Just check if that #OE_ID doesn't exist yet, and if it doesn't - insert the data. If it exists - don't do anything.
Building on the answer from #marc_s. In order to show a message to the user in case there already is a row in the database with the same id, you can check the number of affected rows from the query execution result.
This assumes that the stored procedure only inserts the row if the id is not present and does not emit any errors/exceptions.
Using ADO.NET (with an existing command executing the stored procedure):
Dim affectedRows as Integer = command.ExecuteNonQuery()
If affectedRows = 0 Then
'Handle the error here
MessageBox.Show("There is already a Profile with the supplied id")
Else
'Insert was made
End If
Check the following article to create a SP finding duplicate rows in any table:
http://www.codeproject.com/Articles/157977/Remove-Duplicate-Rows-from-a-Table-in-SQL-Server

View from DB2 to SQL Server 2005

I'm attempting to move a view between DB2 and SQL Server.
CREATE VIEW msu.bad_bus_cnty_st_mstr
AS
SELECT id,
bus_cnty_cntry_cd,
bus_st,
bus_zip
FROM summit.mstr
WHERE ( bus_cnty_cntry_cd, bus_st ) IN (SELECT cnty_cntry_cd,
st
FROM uhelp.cnty_cntry_cd
WHERE
cnty_cntry_descr LIKE '%invalid%');
The view works in DB2, but doesn't work with SQL Server because of the WHERE clause. Can I have a recommendation on how to rewrite this view to work with SQL Server?
It usually helps to define what "doesn't work" means (e.g. what error did you get) and also to specify the version of SQL Server you are using.
Unfortunately SQL Server doesn't support IN() with more than one clause. However you can re-write your view this way:
ALTER VIEW msu.bad_bus_cnty_st_mstr
AS
SELECT id,
bus_cnty_cntry_cd,
bus_st,
bus_zip
FROM summit.mstr AS mstr
WHERE EXISTS
(
SELECT 1
FROM uhelp.cnty_cntry_cd
WHERE cnty_cntry_descr LIKE '%invalid%'
AND cnty_cntry_cd = mstr.bus_cnty_cntry_cd
AND st = mstr.bus_st
);
one way
CREATE VIEW msu.bad_bus_cnty_st_mstr
AS
SELECT id,
bus_cnty_cntry_cd,
bus_st,
bus_zip
FROM summit.mstr m
WHERE EXISTS( SELECT 1 FROM uhelp.cnty_cntry_cd c
WHERE c.cnty_cntry_descr LIKE '%invalid%'
AND c.bus_cnty_cntry_cd = m.bus_cnty_cntry_cd
AND c.st = m.bus_st)

Resources