Use a CURSOR to move data in SQL Server - sql-server

I maintain a list of new contacts that is sent from a subsidiary. Each month a list of contacts is sent to me. The list is complete and I only need the last few dozen rows to be added to the contacts list. I need to maintain the redundant lists for records purposes.
I am trying to use a CURSOR to inspect the monthly inbound tables and place them into master list?

You don't required and should not be using CURSOR to do that.
Basically just use NOT EXISTS to check for existing and insert
INSERT INTO master_list (contact_id, contact_name, . . . )
SELECT contact_id, contact_name, . .
FROM source_contact_list s
WHERE NOT EXISTS
(
SELECT *
FROM master_list x
WHERE x.contact_id = s.contact_id
)

Related

how to return null values from a set of data to show in SQL

So if I'm giving a set of data, and a small part of data are not being inserted into the database, how do I show them as actual "records" in SQL server?
select *
from cleansedcarddatabase
where clientcreditcards in (
'1235980878',
'1235980918',
'1235980969',
'1235980971',
'1235981010',
'1235981014',
'1235981033',
'1235981777',
'1235981321',
'1235981944',
'1235981200'
)
Some of the credit cards clients decided to cancel at last moment, but so those two records never got inserted into database. But I do still want to show those null value cards(since there's no data) from the list of cards(most are inserted). Is there way to do this without temp table?
Let's say I forgot which two card numbers are the ones that didn't got inserted into database, instead just show nothing or the 9 record, anyway to display those two null records as "real" data?
Assuming that you have a column with a card number stored in your database table cleansedcarddatabase called CardNumber, you could reformat your list of card numbers in to a list of values, and then join to your database table on the card number, then display all columns from your database table (because your OP is just using select * from the database table):
select
db_credit_cards.*
from
(values ('1235980878'),
('1235980918'),
('1235980969'),
('1235980971'),
('1235981010'),
('1235981014'),
('1235981033'),
('1235981777'),
('1235981321'),
('1235981944'),
('1235981200')) AS all_credit_cards(CardNumber)
left join cleansedcarddatabase as db_credit_cards ON all_credit_cards.CardNumber = db_credit_cards.CardNumber;
This would allow any records in cleansedcarddatabase to display the data that has been stored there, and then display nulls for the card numbers in your list of values that do not exist in the database table.
If you provide more information regarding the schema cleansedcarddatabase and your actual desired output columns, I can edit this ansewer with a more specific example using this technique.

Enforce link tables

I have two tables, one called Season the other one Episode. Between them is a Link table that stores SeasonID and EpisodeID. How do I make sure that when a new episode is added the Link table will be updated as well?
Assuming that you are using SQL Service.
We can achieve with the help of trigger like this
Query
CREATE TRIGGER trig_Update_Episode
ON [Episode]
FOR INSERT
AS
Begin
IF NOT EXISTS (SELECT 1
FROM [dbo].[tblEpisodeSession] WITH (NOLOCK)
WHERE [EpisodeId] = [inserted.ID])
PRINT N'You must update an entry in tblSessionEpisode As well';
End
for both the table you should create a trigger like given above.
In example query you can replace message with your actual query which should actually create an entry in tblEpisodeSession.
Hope this helps.

SQL views from one table

My colleague asked me a question regarding getting data from a SQL Server database.
I have a sample data set
[ID],[TOWN],[PERSON]
[1],[BELFAST],[JAMES]
[2],[NEWRY],[JOHN]
[3],[BELFAST],[SIMON]
[4],[LARNE],[ALAN]
Now from this I would like to return a SQL Dataset that returns me a different table based upon the view.
Essentially in code I could get a distinct on the town then loop sql filtering on the town. But is there a way I can do this in SQL?
Where I would get (3) views back (2 Belfast, 1 Newry and 1 Larne)
Basicly I it would return
[ID],[Town],[Person]
[1],[Belfast],[James]
[3],[Belfast],[Simon]
Then another view would return for 'Larne' and a Final one for Newry. Basically SQL creating views for each town it finds and then returns the records for each town.
You don't get views back - you have to define them yourself.
E.g. if you need one view for Belfast, a second for Newry and a third for Larne - then you need to create three views that return only those rows that match the relevant city name
CREATE VIEW BelfastView
AS
SELECT ID, Town, Person
FROM dbo.Towns
WHERE Town = 'Belfast'
CREATE VIEW LarneView
AS
SELECT ID, Town, Person
FROM dbo.Towns
WHERE Town = 'Larne'
CREATE VIEW NewryView
AS
SELECT ID, Town, Person
FROM dbo.Towns
WHERE Town = 'Newry'
Now, certain users might only be allowed to select data from the BelfastView and thus would never see any other rows of data from your underlying table.
But views are database objects like tables or stored procedures; you need to create them, maintain them, toss them when no longer needed.
EDIT
Based on your updated question, you simply need to create a view for each town you want to filter:
CREATE VIEW BelfastView AS
SELECT ID,
Town,
Person
FROM YourTable
WHERE Town = 'BELFAST'
Although you've only given us a small sample of your data, what you're asking is almost never a good idea. What happens when you have 50 new towns in your DB? Are you going to create a view for each town? This does not scale well (or at all).
Basically I have decided to Run it as a Stored Procedure to return me each item as a List. So something along the lines of this:
Create Procedure ListTowns
As
declare #towns char(11)
select #towns = (select distinct Town from [Towns])
while #towns is not null <> 0
begin
select * from [YourTable] where Town = #towns
end

how to fill a table with using some of the data of other tables

I need to create a new table called “customer” that include some of columns from the “user table”, and also “project table”. I built my suppliers table with specific column names and I need to fill its column by using data of the other tables. Finally I am trying to finish; when user create a new account and project, the customer table automatically fill with some of other two tables varieties with different column names.
INFO: I have three different user types such as “suppliers”, “costumers”, “managers”. I am holding their information(include user types) in one table called users.
Use the following query as an example and write a query to insert the rows to destination table from source table.
Ex:-
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
Note: Use Join in the select query to join two tables
The 1st step would be to couple the data from the different tables using a table join command. If you can create a search result that matched your new table, then creating the table is simple a call to the below.
Create table CUSTOMER as (Select ...)
"when user create a new account and project.." this is something you plan on doing at run time in your application and not something you need to collate using sql at this point?

Query optimisation in sybase

I need to retrieve customer MSISDN (phone no) from 22 customer databases. I have created a view for two cases:
First we need to check for which MSISDNs profile_id 16240 is inactive.This can be done by querying in database whose inactive data is not null.
Since for GPRS we have two profile 25054 and 16240,it happens e for MSISDNs 25054 (for internet purpose) is active and 16240 (for GPRS is not active)
so we need to create script for that purpose .
I have prepared a query:
CREATE VIEW SUBSCR_INFO_VIEW AS
SELECT subscr_no,account_no FROM CUSTOMER_PROFILE_DEF WHERE subscr_no NOT IN
(SELECT DISTINCT(subscr_no) FROM CUSTOMER_ID_EQUIP_MAP
WHERE inactive_date Is NOT NULL)
AND (profile_id IN (16240) AND cutoff_end_dt IS NOT NULL) OR (profile_id IN (25054) AND profile_id NOT IN (16240) AND cutoff_end_dt IS NULL)
SET ROWCOUNT 100
SELECT DISTINCT(subscr_no) FROM SUBSCR_INFO_VIEW
This will be hit in all 22 customer servers and to take data from a single customer it's taking 2.5 min. I want to reduce that time. Please let me know your feedback.
This is a little difficult to answer without knowing more about the structure of the database. How many records do you have in the CUSTOMER_PROFILE_DEF and CUSTOMER_ID_EQUIP_MAP tables, and what keys do you have? Also, your SQL is very difficult to understand in the original post, I have reformatted it below and made some small changes:
CREATE VIEW
SUBSCR_INFO_VIEW
AS SELECT
subscr_no,
account_no
FROM
CUSTOMER_PROFILE_DEF
WHERE
subscr_no
NOT IN (
SELECT DISTINCT
subscr_no
FROM
CUSTOMER_ID_EQUIP_MAP
WHERE
inactive_date Is NOT NULL
)
AND ((profile_id = 16240 AND cutoff_end_dt IS NOT NULL)
OR (profile_id = 25054 AND cutoff_end_dt IS NULL))
SET ROWCOUNT 100 -- This is just for testing?
SELECT DISTINCT(subscr_no) FROM SUBSCR_INFO_VIEW
The sql is largely the same, but I changed your profile_id in (12345) statements to profile_id = 12345 as there was only one value in the list of values.

Resources