T-SQL stored procedure returns table - sql-server

How do I make a T-SQL stored procedure that returns the (tabular) result of this SELECT statement:
USE automation
SELECT insurer.name,
insurer.case_name,
contact.name,
contact_address.line_1,
contact_address.city,
state.state_abbr,
contact_address.zip
FROM person as insurer
INNER JOIN persons_relationship on persons_relationship.person2_id = insurer.person_id
INNER JOIN person contact on contact.person_id = persons_relationship.person_id
INNER JOIN person_address contact_person_address on contact_person_address.person_id = contact.person_id
INNER JOIN address contact_address on contact_address.address_id = contact_person_address.address_id
INNER JOIN state on state.state_id = contact_address.state_id
insurer.person_class_id = 2

Do something like this:
USE Automation
GO
CREATE PROCEDURE dbo.YourProcedureNameHere
AS
SELECT
insurer.name,
insurer.case_name,
contact.name,
contact_address.line_1,
contact_address.city,
state.state_abbr,
contact_address.zip
FROM
person as insurer
INNER JOIN
persons_relationship on persons_relationship.person2_id = insurer.person_id
INNER JOIN
person contact on contact.person_id = persons_relationship.person_id
INNER JOIN
person_address contact_person_address on contact_person_address.person_id = contact.person_id
INNER JOIN
address contact_address on contact_address.address_id = contact_person_address.address_id
INNER JOIN
state on state.state_id = contact_address.state_id
and you're done. Now you can call your statement as:
EXEC sp_executesql N'dbo.YourProcedureNameHere'

I suggest you also put
SET NOCOUNT ON
Straight after the AS. Some data access libraries are confused by the x records affected message and this turns it off.

put this query in the stored procedure and when you will run this stored procedure you will get tabular result

Related

Multiple INNER JOIN SELECT query not returning data

This is a stored procedure to select the full details of a wine.
It takes as a parameter a storage location ID.
This builds properly and is similar in structure to many sp's I have written that work,
however it returns no data. Is there something I am missing?
CREATE PROCEDURE [sp_retrieveInventory_Full]
(
#StorageLocationID [int]
)
AS
BEGIN
SELECT [WineName],
[RackID],
[RackColumn],
[RackRow],
[WineTypeID],
[WineVarietyID],
[VintnerName],
[dbo].[Vintner].[Country],
[dbo].[Vintner].[StateProvince],
[dbo].[Vintner].[Region],
[VendorName],
[Vintage],
[PurchaseDate],
[PurchasePrice],
[BottleSizeID],
[ABV],
[DrinkByDate],
[FoodType],
[TastingNotes],
[RatedBy],
[RatingScore]
FROM [dbo].[StorageLocation]
INNER JOIN [dbo].[Wine]
ON [dbo].[StorageLocation].[WineID] = [dbo].[Wine].[WineID]
INNER JOIN [dbo].[Vintner]
ON [dbo].[Vintner].[VintnerID] = [dbo].[Wine].[VintnerID]
INNER JOIN [dbo].[Vendor]
ON [dbo].[Vendor].[VendorID] = [dbo].[Wine].[VendorID]
INNER JOIN [dbo].[Pairing]
ON [dbo].[Pairing].[PairingID] = [dbo].[Wine].[PairingID]
INNER JOIN [dbo].[Rating]
ON [dbo].[Rating].[RatingID] = [dbo].[Wine].[RatingID]
WHERE [dbo].[StorageLocation].[StorageLocationID] = #storageLocationID
END
GO
When a query reruns no result it's because no records exists that satisfy the conditions in it's where clause, or, in case of queries that contains inner joins, at least one of the joins on condition returns no records.
The easiest way to figure out what join is messing up your query is to start removing the joins one by one, but to do that, you have to first change the select clause.
What I like to do is this: Start with all the joins except the last one - see if it returns any records:
SELECT 1
FROM [dbo].[StorageLocation]
INNER JOIN [dbo].[Wine]
ON [dbo].[StorageLocation].[WineID] = [dbo].[Wine].[WineID]
INNER JOIN [dbo].[Vintner]
ON [dbo].[Vintner].[VintnerID] = [dbo].[Wine].[VintnerID]
INNER JOIN [dbo].[Vendor]
ON [dbo].[Vendor].[VendorID] = [dbo].[Wine].[VendorID]
INNER JOIN [dbo].[Pairing]
ON [dbo].[Pairing].[PairingID] = [dbo].[Wine].[PairingID]
-- INNER JOIN [dbo].[Rating]
-- ON [dbo].[Rating].[RatingID] = [dbo].[Wine].[RatingID]
WHERE [dbo].[StorageLocation].[StorageLocationID] = #storageLocationID
If not, comment out the next join and run the query again. Rinse and repeat.
Please note, however, that there might be more than one inner join that prevents the query from returning records.

SQL Query to get data from various databases

I wrote the below query to pull the data from different databases. I have created two temp tables to pull the data from two different databases and finally a select statement from the original database to join all the tables. My query is getting executed but not getting any data.(Report is blank). I tried executing the two temp tables separately. it is giving the correct data. But when I execute the whole query, the result is blank. Below is the query. Please help.
"set fmtonly off
use GODSDB
IF object_id('tempdb..#CISIS_Call_Log') IS NOT NULL DROP TABLE #CISIS_Call_Log
select *
into #CISIS_Call_Log
from OPENQUERY (CSISDB,
'select
ccl.ContractOID,
ccl.db_insertdate,
ccl.ContractCallLogStatusIdentifier,
ccl.db_UpdateDate,
ccp.ContractCallLogPurposeOID,
ccp.ContractCallLogPurposeIdentifier,
ccp.Description
from csisdb.dbo.ContractCallLog CCL
inner join csisdb.dbo.ContractCallLogPurpose CCP on ccl.ContractCallLogPurposeIdentifier = ccp.ContractCallLogPurposeIdentifier
where JurisdictionShortIdentifier = ''ON''
AND ContractCallLogStatusIdentifier IN (''DNR'', ''NR'')
')
IF object_id('tempdb..#CMS_Campaign') IS NOT NULL DROP TABLE #CMS_Campaign
select *
into #CMS_Campaign
from OPENQUERY (BA_GBASSTOCMS, '
Select
SystemSourceIdentifier,
ContractOID,
OfferSentDate,
CampaignOfferTypeIdentifier,
CampaignContractStatusIdentifier,
CampaignContractStatusUpdateDate,
DeclineDate,
CampaignOfferOID,
CampaignOID,
CampaignStartDate,
CampaignEndDate,
Jurisdiction,
CampaignDescription
from CMS.dbo.vw_CampaignInfo
where Jurisdiction = ''ON''
and CampaignOfferTypeIdentifier = ''REN''
')
select mp.CommodityTypeIdentifier as Commodity
,c.RtlrContractIdentifier as ContractID
,cs.ContractStatusIdentifier as ContractStatus
,c.SigningDate
,cf.StartDate as FlowStartDate
,cf.EndDate as FlowEndDate
,datediff(day, getdate(), c.RenewalDate) as RemainingDays
,c.RenewalDate
,l.ContractCallLogStatusIdentifier as CallLogType
,Substring (l.Description, 1, 20) as CallPurpose
,l.db_insertDate as CallLogDate
,cms.CampaignOfferOID as OfferID
,cms.CampaignContractStatusIdentifier as OfferStatus
,cms.CampaignContractStatusUpdateDate as StatusChangeDate
,cms.DeclineDate
from Contract c
inner join contractstate cs on cs.contractoid = c.ContractOID
and cs.ContractStatusIdentifier in ('ERA', 'FLW')
and datediff(day, getdate(), c.RenewalDate) > 60
inner join SiteIdentification si on si.SiteOID = c.SiteOID
inner join MarketParticipant mp on mp.MarketParticipantOID = si.MarketParticipantOID
inner join Market m on m.MarketOID = mp.MarketOID
inner join Jurisdiction j on j.JurisdictionOID = m.JurisdictionOID
and j.CountryCode = 'CA'
and j.ProvinceOrStateCode = 'ON'
inner join ContractFlow cf on cf.ContractOID = c.ContractOID
inner join #CISIS_Call_Log l on convert(varchar(15), l.ContractOID) = c.RtlrContractIdentifier
inner join #CMS_Campaign cms on convert(varchar(15), cms.ContractOID) = c.RtlrContractIdentifier
set fmtonly on"
IF the data in each temp table is verified, then:
Try a smaller, less complex, query to test your temp tables with. Also try them using a LEFT join as well e.g.:
select
c.RtlrContractIdentifier as ContractID
, c.SigningDate
, datediff(day, getdate(), c.RenewalDate) as RemainingDays
, c.RenewalDate
, l.ContractCallLogStatusIdentifier as CallLogType
, Substring (l.Description, 1, 20) as CallPurpose
, l.db_insertDate as CallLogDate
, cms.CampaignOfferOID as OfferID
, cms.CampaignContractStatusIdentifier as OfferStatus
, cms.CampaignContractStatusUpdateDate as StatusChangeDate
, cms.DeclineDate
from Contract c
LEFT join #CISIS_Call_Log l on convert(varchar(15), l.ContractOID) = c.RtlrContractIdentifier
LEFT join #CMS_Campaign cms on convert(varchar(15), cms.ContractOID) = c.RtlrContractIdentifier
Does this return data? Does it return data from both joined tables?
If neither temp table is returning data then those join conditions need to be changed.
If both temp tables do return data from that query, then try INNER joins. If that still works, then add back more joins (one at a time) until you identify the join that causes the overall fault.
Without data for every table it just isn't possible for us to pinpoint the exact reason for a NULL result. Only you can, so you need to trouble-shoot the problem one step at a time.

Stored Procedure If / Then Statement

We are trying to implement a password interval, if there is one.
If sm_Setting(PasswordExpireDays) has a value, we use it. If not, continue on
CREATE Procedure user_password_date_interval_check
#ua_pk uniqueidentifier
AS
DECLARE #PasswordExpireDays int
SET #PasswordExpireDays = 0
SELECT
sm_Setting, sm_Value
FROM
Setting_Misc AS sm
INNER JOIN
Syndicates As syn ON sm.syn_fk = syn.syn_pk
INNER JOIN
Company As c ON c.syn_fk = syn.syn_pk
INNER JOIN
User_Accounts As ua ON ua.c_fk = c.c_pk
WHERE
sm.sm_Setting = 'PasswordExpireDays'
THEN sm.sm_Value = #PasswordExpireDays
I'm having issues with the WHERE clause. I have tried CASE. Bottom line is, this row (based on a PK and Setting), I want to grab the value from the Value column.
CREATE Procedure user_password_date_interval_check
#ua_pk uniqueidentifier
AS
DECLARE #PasswordExpireDays int
SELECT
--sm_Setting,
#PasswordExpireDays =COALESCE(sm_Value,0)
FROM
Setting_Misc AS sm
INNER JOIN
Syndicates As syn
ON sm.syn_fk = syn.syn_pk
INNER JOIN
Company As c
ON c.syn_fk = syn.syn_pk
INNER JOIN
User_Accounts As ua
ON ua.c_fk = c.c_pk
WHERE sm.sm_Setting = 'PasswordExpireDays'
--#PasswordExpireDays is either default 0 or the value from the table if not null.

SQL Server stored procedure delete statement

I wish to delete a result a select statement returns, reason I'm doing this is because I have relationships between tables and if I delete from the top-most table its children rows in other tables have to be deleted, too.
Can anyone correct this stored procedure for me please?
ALTER proc [dbo].[storedprocname]
(#Parameter uniqueidentifier = '00000000-0000-0000-0000-000000000000')
AS BEGIN
DELETE FROM TableOne
WHERE IDOne IN
(SELECT
IDOne,
DescOne, IndexOne,
IDTwo,
QuestionTwo, ControlTypeTwo, IndexTwo,
IDThree,
DescThree, IndexThree,
QuestionFour,
OptionFour
FROM
TableOne
INNER JOIN
TableTwo ON TableTwo.CatID = TableOne.IDOne
INNER JOIN
TableThree ON TableThree.Question = TableTwo.IDTwo
LEFT OUTER JOIN
TableFour ON TableFour.Question = TableThree.IDThree
WHERE
TableOne.IDOne = #Parameter)
END
ALTER proc [dbo].[storedprocname]
(#Parameter uniqueidentifier = '00000000-0000-0000-0000-000000000000')
AS BEGIN
DELETE FROM TableOne
WHERE IDOne IN
(SELECT
IDOne
FROM
TableOne
INNER JOIN
TableTwo ON TableTwo.CatID = TableOne.IDOne
INNER JOIN
TableThree ON TableThree.Question = TableTwo.IDTwo
LEFT OUTER JOIN
TableFour ON TableFour.Question = TableThree.IDThree
WHERE
TableOne.IDOne = #Parameter)
END
Since you want to delete all rows where IDOne is in a list of possible values - then you need to make sure the subquery after the IN (...) also returns a single column which can be used to compare! After all, you cannot compare a single IDOne value to the whole list of columns that you're currently returning ....
Try something like this:
ALTER proc [dbo].[storedprocname]
(#Parameter uniqueidentifier = '00000000-0000-0000-0000-000000000000')
AS BEGIN
DELETE FROM TableOne
WHERE IDOne IN
(SELECT
IDOne
FROM
TableOne
INNER JOIN
TableTwo ON TableTwo.CatID = TableOne.IDOne
INNER JOIN
TableThree ON TableThree.Question = TableTwo.IDTwo
LEFT OUTER JOIN
TableFour ON TableFour.Question = TableThree.IDThree
WHERE
TableOne.IDOne = #Parameter)
END
I don't know (your question is too vague and not clear enough) whether all those JOIN's inside the subquery are really needed .... you might need to tweak that to your requirements.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Need some SQL syntax help :-)
Both databases are on the same server
db1 = DHE
db2 = DHE_Import
UPDATE DHE.dbo.tblAccounts
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink
ON DHE.dbo.tblAccounts.AccountCode = DHE_Import.tblSalesRepsAccountsLink.AccountCode
SET DHE.dbo.tblAccounts.ControllingSalesRep = DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
I can do a query in Access with linked tables with similar syntax - BUT SQL doesn't like it.
I'm sure it's a simple issue :-D
Thanks!
You could call it just style, but I prefer aliasing to improve readability.
UPDATE A
SET ControllingSalesRep = RA.SalesRepCode
from DHE.dbo.tblAccounts A
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink RA
ON A.AccountCode = RA.AccountCode
For MySQL
UPDATE DHE.dbo.tblAccounts A
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink RA
ON A.AccountCode = RA.AccountCode
SET A.ControllingSalesRep = RA.SalesRepCode
Following is the MySQL syntax:
UPDATE table1
INNER JOIN table2 ON table1.field1 = table2.field2
SET table1.field3 = table2.field4
WHERE ...... ;
http://geekswithblogs.net/faizanahmad/archive/2009/01/05/join-in-sql-update--statement.aspx
Sorry its late, but I guess it would be of help to those who land here finding a solution to similar problem.
The set clause should come right after the update clause. So rearranging your query with a bit change does the work.
UPDATE DHE.dbo.tblAccounts
SET DHE.dbo.tblAccounts.ControllingSalesRep
= DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink
ON DHE.dbo.tblAccounts.AccountCode
= DHE_Import.tblSalesRepsAccountsLink.AccountCode
UPDATE table1 a
inner join table2 b on (a.kol1=a.b.kol1...)
SET a.kol1=b.kol1
WHERE
a.kol1='' ...
for me until the syntax worked -MySQL
Should look like this:
UPDATE DHE.dbo.tblAccounts
SET DHE.dbo.tblAccounts.ControllingSalesRep =
DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink
ON DHE.dbo.tblAccounts.AccountCode =
DHE_Import.tblSalesRepsAccountsLink.AccountCode
Update table is repeated in FROM clause.
which may be useful
Update
A INNER JOIN B ON A.COL1=B.COL3
SET
A.COL2='CHANGED', A.COL4=B.COL4,......
WHERE ....;
It is very simple to update using Inner join query in SQL .You can do it without using FROM clause. Here is an example :
UPDATE customer_table c
INNER JOIN
employee_table e
ON (c.city_id = e.city_id)
SET c.active = "Yes"
WHERE c.city = "New york";
It is explained here http://erabhinavrana.blogspot.in/2014/01/how-to-execute-update-query-by-applying.html
It also has other useful code snippets which are commonly used.
update <dbname of 1st table>.<table name of 1st table> A INNER JOIN <dbname of 2nd table>.<table name of 2nd table> RA ON A.<field name of table 1>=RA.<field name of table 2> SET A.<field name of table 1 to be updated>=RA.<field name of table 2 to set value in table 1>
Replace data in <> with your appropriate values.
That's It.
source:
http://www.dynamic-coders.com/how-to-update-two-different-tables-in-different-databases-on-same-server
//For Access Database:
UPDATE ((tblEmployee
LEFT JOIN tblCity ON (tblEmployee.CityCode = tblCity.CityCode))
LEFT JOIN tblCountry ON (tblEmployee.CountryCode = tblCountryCode))
SET tblEmployee.CityName = tblCity.CityName,
tblEmployee.CountryName = tblCountry.CountryName
WHERE (tblEmployee.CityName = '' OR tblEmployee.CountryName = '')
Update one table using Inner Join
UPDATE Table1 SET name=ml.name
FROM table1 t inner JOIN
Table2 ml ON t.ID= ml.ID
Worked perfectly for me.
UPDATE TABLE_A a INNER JOIN TABLE_B b ON a.col1 = b.col2 SET a.col_which_you_want_update = b.col_from_which_you_update;

Resources