Stored Procedure to display values from sql server - sql

I am developing a windows application in vb.net. I have a requirement to retrieve values from a table based on certain criteria. My sql server table is as below.
tbl ACCOUNT_DETAIL
I have a textbox in my windows form for displaying the corresponding GL_Account. The user will pass the paidto value to the back end and the procedure must return the corresponding GL_Account. But there is one more criteria : while retrieving the GL_Account from the database, we need to check for wholefamily. If the WholeFamily is 1 then all the Accounts(should be fetched from another table) which starts with the GL_Account should be retrieved. Else only the GL_Account from "this" table needs to be sent. The table which contains the entire account information is below
tbl ACCOUNT_MASTER.
I have shown only a part of the data from the table here.
I have created a Cursor to fetch values from the Account_Detail table. But after fetching values i need to check for WholeFamily and based on the bit i need to pass values to the front end.
#PaidTo(int) is the SP Parameter that is passed from the frontend.
DECLARE #GLAccount VARCHAR(50)
DECLARE #AccountName VARCHAR(MAX)
DECLARE PV_CURSOR CURSOR
FOR
SELECT GL_Account,WholeFamily
FROM ACCOUNT_DETAIL
WHERE PaidTo=#PaidTO
OPEN PV_CURSOR
FETCH NEXT FROM PV_CURSOR
INTO #GLAccount,#AccountName
Now I am stuck as to how to proceed further. Sorry for my ignorance.
Please help me.

I would not use a cursor in such a scenario...
If I understand what you are suggesting correctly, incase Whole_family is 1 then you need to pull all info from the other table in the same result set. The below query can have multiple rows for every GL_Account based on your entries in the Account_master.
SELECT PAIDTO
, GL_ACCOUNT
, WHOLEFAMILY
, ACCOUNTNUMBER
, ENGLISHNAME
FROM ACCOUNT_DETAIL
LEFT JOIN ACCOUNT_MASTER
ON CASE
WHEN WHOLEFAMILY = 1
THEN ACCOUNT_DETAIL.GL_ACCOUNT
ELSE NULL
END = ACCOUNT_MASTER.ACCOUNTNUMBER

Related

Adding additional unique Row ID to existing table

I have the below code where I assign an unique ID to each row which contains a current code and a previous code. It seems to be working fine but my question is if I have an updated file with new codes, how do I resume the unique ID from where it was left off?
For example, how do I populate the below ID highlighted in yellow if I add these additional row?
Example
CREATE PROCEDURE [dbo].[PI_Key_Create_Update] AS
BEGIN
Truncate Table RB_PI_Key_Assign
Truncate Table RB_PI_Key_Link
INSERT INTO RB_PI_Key_Assign
SELECT
ROW_NUMBER() OVER (ORDER BY RB_Code_L) AS PI_Key
, RB_Code_L
, RB_Code_L_P
FROM Stage_RB_Previous
INSERT INTO RB_PI_Key_Link
SELECT
a.PI_Key
, b.PI_Key as PI_KEY_P
, a.RB_Code_L
, a.RB_Code_L_P
FROM RB_PI_Key_Assign a LEFT JOIN RB_PI_Key_Assign b ON (a.RB_Code_L_P=b.RB_Code_L)
END
Thanks
first and foremost this type of columns should be identity seeded or autoincrement. You don't need to maintain them.
There is nothing special if you have them manually updated for no reason at all.

access 2010 append data into table without overwriting existing records

Sorry for the long question/post but need some help as I've been searching for several days but havent found anything that helps. Seems like it should be easy but..here goes
I have table1 in my (Access 2010) database that has exising records. I have another table2 that after I run a query, it first deletes the data in table 2, then imports new records into that table. I run the import into table 2 on a semi regular basis but have yet to copy all those records into table 1 successfully.
I need to copy only the records from table 2 to table 1 if the records don't already exist in table1. So, each time the query or vba code would run, it would be continuing to grow table 1 without duplicating existing data.
To clarify further, it's data from the Outlook GAL so each time table2 imports that data (lname,fname,phone,email) it needs to be added to table1, but only if it doesn't already exist in table 1.
I have a small start of SQL but cannot get it to work properly because I'm not sure how to add the other fields into this SQL statement properly (unfortunately I don't know a whole lot about SQL or creating an append query):
INSERT INTO [Current] ( FirstName )
SELECT DISTINCT tblglobaladdresslistimport.First
FROM tblglobaladdresslistimport LEFT JOIN [Current] ON tblglobaladdresslistimport.First = Current.FirstName
WHERE Current.FirstName Is Null;
How about this :
INSERT INTO [Current](FirstName, LastName, Phone, Email)
SELECT DISTINCT
tblglobaladdresslistimport.First
, tblglobaladdresslistimport.Last
, tblglobaladdresslistimport.Phone
, tblglobaladdresslistimport.Email
FROM
tblglobaladdresslistimport LEFT JOIN [Current]
ON tblglobaladdresslistimport.First = Current.FirstName
AND tblglobaladdresslistimport.Last = Current.LastName
AND tblglobaladdresslistimport.Phone = Current.Phone
AND tblglobaladdresslistimport.Email = Current.Email
WHERE Current.FirstName Is Null
AND Current.LastName Is Null
AND Current.Phone Is Null
AND Current.Email Is Null;
Adjust column names if I guessed it wrong. That assumed that you don't have primary key, so data in tblglobaladdresslistimport considered already exists if there is a row in Current having same value for all columns.

Selecting parameter from values of a SQL Query

I need to produce a report that selects a set of values from a database table based on a company. I would like the user to be able to select the name of the company from a list of available companies. The companies have 2 associated unique database ID code number. Based on what companies the user selects I need the sql query to pass to the parameter both unique codes to the parameter.
So, in short, how do I create a sql query that would show the company names and when selecting the company would then select both unique codes based on the company name I select from a single select drop down. Use the value selected from that drop-down list to run the SQL query in the report itself?
Thanks for any help or advice you can offer!
Pass the company name to to your stored proc instead of the two unique codes, then find the codes for the company inside your procedure.
CREATE someProc (#Company VARCHAR(100))
AS BEGIN
DECLARE #ID1 INT, #ID2 INT
SELECT #ID1 = someID1, #ID2 = someID2
FROM someDatabase
WHERE companyName=#Company

SQL: I need to take two fields I get as a result of a SELECT COUNT statement and populate a temp table with them

So I have a table which has a bunch of information and a bunch of records. But there will be one field in particular I care about, in this case #BegAttField# where only a subset of records have it populated. Many of them have the same value as one another as well.
What I need to do is get a count (minus 1) of all duplicates, then populate the first record in the bunch with that count value in a new field. I have another field I call BegProd that will match #BegAttField# for each "first" record.
I'm just stuck as to how to make this happen. I may have been on the right path, but who knows. The SELECT statement gets me two fields and as many records as their are unique #BegAttField#'s. But once I have them, I haven't been able to work with them.
Here's my whole set of code, trying to use a temporary table and SELECT INTO to try and populate it. (Note: the fields with # around the names are variables for this 3rd party app)
CREATE TABLE #temp (AttCount int, BegProd varchar(255))
SELECT COUNT(d.[#BegAttField#])-1 AS AttCount, d.[#BegAttField#] AS BegProd
INTO [#temp] FROM [Document] d
WHERE d.[#BegAttField#] IS NOT NULL GROUP BY [#BegAttField#]
UPDATE [Document] d SET d.[#NumAttach#] =
SELECT t.[AttCount] FROM [#temp] t INNER JOIN [Document] d1
WHERE t.[BegProd] = d1.[#BegAttField#]
DROP TABLE #temp
Unfortunately I'm running this script through a 3rd party database application that uses SQL as its back-end. So the errors I get are simply: "There is already an object named '#temp' in the database. Incorrect syntax near the keyword 'WHERE'. "
Comment out the CREATE TABLE statement. The SELECT INTO creates that #temp table.

SQL query select from table and group on other column

I'm phrasing the question title poorly as I'm not sure what to call what I'm trying to do but it really should be simple.
I've a link / join table with two ID columns. I want to run a check before saving new rows to the table.
The user can save attributes through a webpage but I need to check that the same combination doesn't exist before saving it. With one record it's easy as obviously you just check if that attributeId is already in the table, if it is don't allow them to save it again.
However, if the user chooses a combination of that attribute and another one then they should be allowed to save it.
Here's an image of what I mean:
So if a user now tried to save an attribute with ID of 1 it will stop them, but I need it to also stop them if they tried ID's of 1, 10 so long as both 1 and 10 had the same productAttributeId.
I'm confusing this in my explanation but I'm hoping the image will clarify what I need to do.
This should be simple so I presume I'm missing something.
If I understand the question properly, you want to prevent the combination of AttributeId and ProductAttributeId from being reused. If that's the case, simply make them a combined primary key, which is by nature UNIQUE.
If that's not feasible, create a stored procedure that runs a query against the join for instances of the AttributeId. If the query returns 0 instances, insert the row.
Here's some light code to present the idea (may need to be modified to work with your database):
SELECT COUNT(1) FROM MyJoinTable WHERE AttributeId = #RequestedID
IF ##ROWCOUNT = 0
BEGIN
INSERT INTO MyJoinTable ...
END
You can control your inserts via a stored procedure. My understanding is that
users can select a combination of Attributes, such as
just 1
1 and 10 together
1,4,5,10 (4 attributes)
These need to enter the table as a single "batch" against a (new?) productAttributeId
So if (1,10) was chosen, this needs to be blocked because 1-2 and 10-2 already exist.
What I suggest
The stored procedure should take the attributes as a single list, e.g. '1,2,3' (comma separated, no spaces, just integers)
You can then use a string splitting UDF or an inline XML trick (as shown below) to break it into rows of a derived table.
Test table
create table attrib (attributeid int, productattributeid int)
insert attrib select 1,1
insert attrib select 1,2
insert attrib select 10,2
Here I use a variable, but you can incorporate as a SP input param
declare #t nvarchar(max) set #t = '1,2,10'
select top(1)
t.productattributeid,
count(t.productattributeid) count_attrib,
count(*) over () count_input
from (select convert(xml,'<a>' + replace(#t,',','</a><a>') + '</a>') x) x
cross apply x.x.nodes('a') n(c)
cross apply (select n.c.value('.','int')) a(attributeid)
left join attrib t on t.attributeid = a.attributeid
group by t.productattributeid
order by countrows desc
Output
productattributeid count_attrib count_input
2 2 3
The 1st column gives you the productattributeid that has the most matches
The 2nd column gives you how many attributes were matched using the same productattributeid
The 3rd column is how many attributes exist in the input
If you compare the last 2 columns and the counts
match - you can use the productattributeid to attach to the product which has all these attributes
don't match - then you need to do an insert to create a new combination