Transact SQL :: Getting Correct Results From Two Tables?

Oct 5, 2015

We have two tables. 

Table1:
Servers | Numbers
------------
Server1 | 1
Server1 | 2
Server1 | 3
Server2 | 1
Server2 | 2
Server2 | 4
Server3 | 2
Server3 | 5
Server3 | 9
Server3 | 7
.....

Table2:
         | Numbers
-----------
NULL | 1
NULL | 2
NULL | 3

I need to select Server1, Server2, Server3 and other servers that does not have correct value in Table2. Results should return server name and number that server does not have like:

Server2 | 3
Server3 | 1
Server3 | 3

Table1 is updated time to time, Table2 - static table. The best would be to avoid loop or cursor. Is that possible to get these results in one query?

View 4 Replies


ADVERTISEMENT

Transact SQL :: UPDATE Statement - Returns Correct Results When Running Separately

May 1, 2015

SQL Ver: 2008 (not r2)
Problem:  The following code returns correct results when moving variable declarations and update statement outside a stored procedure, but fails to return a value other than zero for the "COMPANY TOTAL" records.  The "DEPT TOTAL" result works fine both in and outside the sp.This may have to do with handling NULL values since I was getting warning message earlier involving a value being eliminated by an aggregate function involving a NULL.  I only got this message when running inside the sp, not when running standalone.  I wrapped the values inside the SUM functions with an ISNULL, and now return a zero rather than NULL for the "COMPANY TOTAL" records when running inside SP.All variable values are correct when running.

SQL CODE:
DECLARE 
     @WIPMonthCurrent date = (SELECT TOP 1 WIPMonth FROM budxcWIPMonths WHERE ActiveWIPPeriod = 'Y')
  select @WIPMonthCurrent as WIPMonthCurrent
  
[code]....

View 10 Replies View Related

Sql Query Not Returning Correct Results From Db

Feb 6, 2006

Hello.

I am new at SQL and am using SQL server express edition and im a bit stuck! I am using ASP.NET and C# in my website which is using sql database back end.

String SQLroom = "SELECT DISTINCT RoomName FROM Room INNER JOIN RoomCalendar ON Room.RoomID = RoomCalendar.RoomID WHERE Capacity = '" + reqCapacity + "' " + " AND NOT ('" + newRoomEnd + "' <= roomStartDateTime OR '" + newRoomStart + "' >= roomEndDateTime) AND (OHP = '" + ohpYesNo + "' AND AV = '" + avYesNo + "') ";

This is my SQL string... what it is trying to do is:

find the room
where the capacity is the reqcapacity entered by user
and the startdatetime and enddatetime entered by the user are not present in the table for that room capacity
and then look at whether the user requires OHP or AV facilities, which are stored in the database as either yes or no values.
The problem i am having is with the condition in the sql query... because the user may require an OHP and not AV, but then the room returned "`could" have AV facilities, as it wouldnt make a difference to them if it was there or not, basically, the yes condition has to be satisfied.

Not sure whether i should be using AND, or OR? or a combination.

Any ideas gratefully appreciated....

Sandy

View 2 Replies View Related

Transact SQL :: Want To Correct Database Design

Apr 29, 2015

I have below database already on one of the environment and its surprisingly designed somewhat in the past.now I want to correct it with one default filegroup with one primary and one log file, same time i am concerned for data as its production and no test environment is there, any way which ensure full consistency and steps i need to do...

CREATE
DATABASE [Sample]
ON 
PRIMARY
(
NAME =
N'Sample_Data',

[code]....

View 11 Replies View Related

Transact SQL :: How To Find If Email Is Of Correct Format

Aug 13, 2015

I am getting email from the end client and i need to validate in sql query.

View 3 Replies View Related

Transact SQL :: Standard And Correct Cursor Format

Aug 12, 2015

I have a table which is a configuration table, I have declared cursors whereby the cursor doesn't get to all the rows in the configuration table even though there is no where clause in the select statement and the cursor ought to loop/go through every single row. Changed the cursor to the below and it started to go through all rows.

DECLARE XXX CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY TYPE_WARNING FOR

Now with the definition above, I am now having a situation whereby a column in row 1 which is a bit data type and has a value of 0, then the cursor gets to row 2 the same column but with a value of 1 and an if statement in the cursor saying

IF @row2columnX = 0 set @myval = 99

For some reason within the cursor the IF statement is being implemented even though the value in row2 columnX is = 1

I find it so weird. Is there a database property that affects the way cursors react or is there something that I am doing incorrectly ? Lastly, I would like to have a simple cursor template which simply goes through a configuration table or any table.

View 11 Replies View Related

Transact SQL :: BULK INSERT Not Importing Correct Data For Field?

May 14, 2015

I am using a BCP format file to import a CSV file. The file looks like the following:

"01","02"

The format file looks like the following:

6.0                                                                                     
2                                                                                      
1      SQLCHAR    0      0       """         0    ""
2      SQLINT       0      0       "",""     1   MROS
3      SQLINT       0      0       ""
"   2   MROF

When both the two fields are set to SQLCHAR data types the data imports successfully without the quotes as 01 and 02.  These fields will always be numbers and I want them as integers so I set the data type to int in the database and SQLINT in the format file.  The results was that the 01 became 12592 and the 02 became 12848.  where these numbers are coming from?

View 7 Replies View Related

Correct Way Of Finding A Tables Primary Keys??

Aug 7, 2007

Hope this is in the right thread, sorry if not!

I have run into a problem, i need to find out that column(s) in a table that makes the primary key.
I thought that this code did the trick.
***
DECLARE @c varchar(4000), @t varchar(128)
SET @c = ''
SET @t='contact_pmc_contact_relations'
Select @c = @c + c.name + ',' FROM syscolumns c INNER JOIN sysobjects o ON o.id = c.id inner join sysindexkeys k on o.id = k.id WHERE o.name = @t and k.colid = c.colid ORDER BY c.colid
SELECT Substring(@c, 1, Datalength(@c) - 1)
***

This works in most of my cases. But i have encounterd tabels where this code doesn't work.
Here is a dump from one of the tabels where it doesn't work.
SELECT *
FROM sysindexkeys
WHERE (id = 933578364) <--id of the table
***
id indid colid keyno
933578364 1 1 1
933578364 1 2 2
933578364 2 1 1
933578364 3 2 1
933578364 4 3 1
933578364 5 4 1
933578364 6 5 1
933578364 7 6 1
933578364 8 7 1

Not sure if that dump made any sense, but i hope it did.
If i look at the table in SQL Enterprise manager there is no relations, no indexes only my primarykey made up with 2 columns (column id 1 and 2).

So, anyone know how i could solve this problem?


Regards
/Anders

View 8 Replies View Related

Dependencies Not Correct With Temporary Tables --&&> Replication Is Failing

Jul 13, 2006

Hello all,

here is a stored procedure I have:

CREATE PROCEDURE spU_GUI_AppliqueConditionFinancementPourGuichet
(
@GuichetId int,
@Validateur nvarchar(40)
)
AS
CREATE TABLE #tReservations (ReservationId int)

IF (dbo.GetSiGuichetEnRegle(@GuichetId) = 0)
INSERT #tReservations
EXECUTE spU_GUI_AppliquePerteFinancement @GuichetID, @Validateur
ELSE
INSERT #tReservations
EXECUTE spU_GUI_AppliquePerteAgrement @GuichetID, @Validateur


SELECT GR.Id,
dbo.FormateNoms(GR.Name) AS Names
FROM #tReservations
LEFT JOIN AnotherTable GR ON GR.Id = AnotherTable.id

DROP TABLE #tReservations
GO


The creation is ok but when I look to the dependencies, I see that it depends on GetSiGuichetEnRegle only.

For me, it shall also depend on

AnotherTable
spU_GUI_AppliquePerteFinancement
spU_GUI_AppliquePerteAgrement
FormateNoms

Apparently the dependencies are not calculated correctly because I'm using a temporary table.

My problem is that I have updated this stored procedures (and the two other that I call) to add a new parameter. As a consequence, when I do a replication, this is failing saying that I have an extra parameter. I imagine that because my dependencies are not correct, the replication is not occuring in the correct order and so it's still using the old definition of the stored procedure.

Do you have any idea on how I can force the dependencies to be calculated correctly ?

Thanks

View 3 Replies View Related

Correct Way To Insert Data Into Multiple Tables (Stored Procedure)

Nov 3, 2007



Hi

I am currently developing my first database driven application and I have stumbled over some quite simple issue. I'll describe my database design first:
I have one table named images(id (identity), name, description) and one table named albums (id, name, description). Since I'd like to establish a n:n connection between these, I defined an additional table ImageInAlbum (idImage, idAlbum). The relation between these tables works as expected (primary keys, foreign keys appear to be ok).

Now I'd like to insert data via a stored procedure in sql server 2005 and I'm not sure how this procedure will look like.
To add a simple image to a given album, I am trying to do the following:
* Retrieve name, description from the UI
* Insert a new row into images with this data
* Get the ID from the newly created row
* Insert a new row into "ImageInAlbum" with the ID just retrieved and a fixed Id from the current album.

I know how I would do the first two things, but I am not used to Stored Procedures syntax yet to know how to do the other things.

Any help is appreciated ... even if it means telling me that I am doing something terribly wrong

View 9 Replies View Related

Correct Syntax To Pull Back Duplicate Vendors Based On 6 Fields From Two Different Tables

Feb 20, 2015

I'm looking for the correct syntax to pull back duplicate vendors based on 6 fields from two different tables. I want to actually see the duplicate vendor information (not just a count). I am able to pull this for one of the tables, something like below:

select *
from VendTable1 a
join ( select firstname, lastname
from VendTable1
group by firstname, lastname
having count(*) > 1 ) b
on a.firstname = b.firstname
and a.lastname = b.lastname

I'm running into issues when trying to add the other table with the 4 other fields.

View 5 Replies View Related

Transact SQL :: Getting Results As Raw Text?

Sep 4, 2015

I am working on an HTTP POST application where I am using SQL to return "message" based text results.

A typical query would yield a message something like:

135,15,1,1,1,4,1,1,1,"NAME"

I now have a requirement to have the same query return several rows, but when i send them, they need to be a single message containing several records delimited by CRLF, yielding (1) message, so the result set would look like:

135,15,1,1,1,4,1,1,1,"NAME"
135,15,2,1,1,2,2,3,2,"TestName"
135,15,3,1,1,4,1,1,1," 41"
135,15,4,1,1,4,1,1,1,"asd"

how to do this?

View 3 Replies View Related

Transact SQL :: How To Get Query Results To CSV File

Sep 16, 2015

After running a query (from the Query Builder) in SQL Server 2008 sometimes I can right-click on the results pane and "Save results as CSV file", other times it's not an option.  After running a query for 24 hours (several million record results) I can't seem to do anything with the results. I have my settings:

Options | Query results | SQL Server | Default Destination for Results

set to "Results to File" and a path entered, but it doesn't work.  Is there wording I can add to the end of my SQL statement such as "TO FILE xxx.csv" or something?

View 4 Replies View Related

Transact SQL :: How To Get Sum Of Results From GROUPING SETS

Jul 8, 2015

I needed to add in the Fiscal Year (FY) to group my results by FY.  I changed my code to the following:

/*
EXEC ADAMHsp_BSS_GetNonMedicaidReportTotals
@pstrProviderName = 'FAM SER-WOOD'
*/

ALTER PROCEDURE [dbo].[ADAMHsp_BSS_GetNonMedicaidReportTotals]
@pstrProviderNameVARCHAR(100)
AS
BEGIN

[Code] ....

See my result set in the picture below.  The rows with NULL in the 'ProcGrp' column have the totals of the groupings by FY that I am looking for - that's great.  What I want to do now is have another row that contains the sums of the values from any row where 'ProcGrp' is null so that I have a totals row.

View 3 Replies View Related

Transact SQL :: Pivot On Multiple Results

Nov 9, 2015

I have a table similar to below:

itemID | part
1         | A
1         | B
2         | A
2         | A
2         | A
3         | C

I need the table to look like the following:

itemID | part1 | part2 | part 3
1         | A        | B       | null
2         | A        | A       | A
3         | C        | null    | null

There will _never_ be more than three parts to an item, and it does not matter what order they are in.

I cannot get pivot to work for me.

View 2 Replies View Related

Transact SQL :: Possible To Use Results From OUTPUT And Use Them As Parameters?

May 28, 2015

I am trying to create a proc and at the end of the proc I want to call another proc and pass to one of the parameters to proc using the result from the "OUTPUT". Is it possible to use the results from the "OUTPUT" and use them as parameters?

USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[code]....

View 16 Replies View Related

Transact SQL :: Stored Procedure To Return Results

May 27, 2015

How can I return results from this SP?

Alter
Procedure  sp_Blocking
as
      SET NOCOUNT
ON
truncate
table blocked

[Code] ....

View 4 Replies View Related

Transact SQL :: Group Results Into Single String

Jun 4, 2015

I have a query that pulls back task and user assigned. Each task can have multiple users assigned. I want to pull back the single task and all the users assigned in one row. 

Current Query:

select
t.Name 'Task',
d.FirstName + d.LastName 'User'
from [dbo].[Tasks_TemplateAssignTo] a join
Task_Template t on a.template_id = t.ID join
Doctor d on d.id = a.provider_id

Results from query above:

TaskUser
Call CustomerJohn Smith
Call CustomerBetty White
Call CustomerTammy Johnson
Order suppliesGreg Bullard
Order suppliesJosephine Gonzalez

Expected Results:

TaskUser
Call CustomerJohn Smith, Betty White, Tammy Johnson
Order SuppliesGreg Bullard, Jospehine Gonzalez

View 4 Replies View Related

Transact SQL :: Send Email Only If Query Contains Results

Aug 8, 2015

I’m running a data integrity procedure from an agent job that is a scheduled weekly maintenance task which emails the results of my query, and is working properly.

I would however like this to only receive the email it the query contains results, and not send it no records are found to prompt me to take action.
 
My code less the personal information
  
EXEC msdb.dbo.sp_send_dbmail     
@profile_name
= '',
       @recipients
= '',
       @subject
= 'Database Integrity - Import Errors',

[Code] ....

View 5 Replies View Related

Transact SQL :: Update Based On Results From Select

Jul 24, 2015

Update statement based on the results from this SELECT:

SELECT RELQ_REL_VERSION_NM,
RELQ_RELEASE_Q_ID,
RELQ_STATUS_CD,
RELSP_RELEASE_STEP_ID,
RELSP_STEP_TYPE_CD,
RELSP_STATUS_CD
FROM RELEASE_QUEUE WITH (NOLOCK)

[Code] ....

I need to update all records where the 

RELEASE_STEPS.RELSP_STATUS_CD = 'SKPD'TORELEASE_STEPS.RELSP_STATUS_CD = 'CMPS'

I imagine that the UPDATE statement will be something like:

UPDATE RELEASE_STEPS SET dbo.RELEASE_STEPS.RELSP_STATUS_CD = 'CMPS'
WHERE (
SELECT RELQ_REL_VERSION_NM,
RELQ_RELEASE_Q_ID,
RELQ_STATUS_CD,
RELSP_RELEASE_STEP_ID,
RELSP_STEP_TYPE_CD,

[Code] .....

View 4 Replies View Related

Transact SQL :: Generating XML (serialized) From Query Results

Aug 20, 2015

I didn't work with XML before and so I'm posting this question on how we can generate serialized XML. I have the following table -

DECLARE @Population TABLE (CountryId INT IDENTITY(1,1), CountryName VARCHAR(15), StateName VARCHAR(20), PopulationCount INT)
INSERT INTO @Population (CountryName, StateName, PopulationCount)
VALUES ('USA','California',300000),
('USA','Chicago',500000),
('Australia','Queensland',550000),

[Code] ....

Please note that I can have another country with 10 states or 30 states, so State Name is dynamic. Can this be done in SQL ? or we have to use .NET ?

SQLServer2014
-12.0.2000.8(X64)

View 6 Replies View Related

Transact SQL :: How To Get Zero Or Null Value For Empty Results In Server

Oct 7, 2015

I have written one query like this 

select staffid,staffname,deptname

From staff s join dept d on s.deptid=d.deptid

This query we have no results 

I need this results

staffid staffname deptname
null     null          null

View 7 Replies View Related

Transact SQL :: EXCEPT Not Showing The Results - Zero Rows Returned

Sep 10, 2015

I have two tables A and B, A has 8000 and B has 8122 records. I want to see what records are missing. I tried EXCEPT and it returned zero rows. I used where non exists also still no records.

View 5 Replies View Related

Transact SQL :: How To Get Results Based On Conditional Where Clause

Jul 14, 2015

My source table has two columns... Policynum and PolicyStartdate and data looks like..
.
Policynum              PolicyStartdate
123G                       01/01/2012    
456D                       02/16/2012     
789A                       01/21/2012
163J                       05/25/2012

Now my output should return based on 3 parameters..

First two parameters are date range... let say @fromdt and @todt

Third parameter is @policynum

Scenario-1: Enter dates in date range param and leave policynum param blank
Ex: policystartdate between '01/01/2012 and '01/31/2012'.... It returns 1st and 3rd rows from above in the output

Scenario-2: enter policy num in policynum param and don't select any dates
Ex:  policynum ='456D'     It returns 2nd row in the output

Scenario-3: Select dates in date range param and enter policynum in param
Ex: policystartdate between '01/01/2012 and '01/31/2012' and policynum
='163J'.  it should return only 4th row even though dates were selected(Override date range when policynum is entered in param and just return specified policynum row in the output)

I need t-sql code to get above results.

View 12 Replies View Related

Transact SQL :: If Statement Matches Multiple Results

Jun 2, 2015

If it possible to have an if statement match multiple results, as to not have to use the OR multiple times.

Example: I want to say, if Description equals red or blue or green or yellow or orange or black or white or pink, without having to use OR and OR and OR.  Description can match 10 different values.

View 9 Replies View Related

Transact SQL :: GetDate Function Not Returning Any Results?

May 27, 2015

I am having a problem with the GETDATE().

WHERE TableName.ColumnNamne = Getdate()

The above SQL function does not return any results whereas the below SQL code returns results. Am I doing anything wrong?

WHERE SalesOrder.New_ActualShipmentDate >= GETDATE()

View 35 Replies View Related

Transact SQL :: Delete Statement From Select Results

Jul 24, 2015

I'm trying to delete the selected data from a table colum from a select statement.

This is the select statement

SELECT  RFC822  FROM  SQLGOLDMINE.DBO.MAILBOX MB WHERE ((MB.CREATEON >= '2014-07-24' AND MB.CREATEON <= '2015-07-24') OR (MB.MAILDATE >= '2014-07-24' AND MB.MAILDATE <= '2015-07-24')) AND (MB.MAILREF LIKE '%auction notification
& invitation%')

What the delete statement would look like. I've tried replacing Select with delete from but get a sytax error.

View 9 Replies View Related

Transact SQL :: How To Join Results Of Two Queries By Matching Columns

Aug 10, 2015

I have two queries as below;

SELECT EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours
FROM dbo.tblEventStaffRequired;

and
SELECT EventID, Role, StartTime, EndTime, Hours, COUNT(ID) AS Booked
FROM tblStaffBookings
GROUP BY EventID, Role, StartTime, EndTime, Hours;

How can I join the results of the two by matching the columns EventID, Role, StartTime and EndTime in the two and have the following columns in output EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours and Booked?

View 4 Replies View Related

Transact SQL :: Insert Trigger Returning Incorrect Results

Jul 11, 2015

SQL Version:  SQL2014

PROBLEM:  The SQL insert trigger code below is returning incorrect results.  In some cases the results returned are from entirely different fields than those specified as the source field in the SET statement.  For instance the value returne for the Price_BeforeAdj field does not = 20000000?  It returns a NULL.  See code below.

OFFENDING CODE:

ALTER TRIGGER [dbo].[xcti_WIPAdjustments_I]
   ON  [dbo].[budxcWIPAdjustments]
AFTER INSERT AS
BEGIN
 SET NOCOUNT ON;
  UPDATE budxcWIPAdjustments

[Code] ....

View 11 Replies View Related

Transact SQL :: Transform Duplicate Rows From Query Results To One Row

Jun 16, 2015

I have three tables, Accounts, AccountCustomer and Customers, and the data-relationshiop between are defined according to the image below:

I created also a query (the sql-query below), displaying the customers for every account that is on the table "Accounts", and I got the results, as we can see in the image below:

SELECT A.AccountID,
c.CustomerNo,
c.Surname,
c.Name,
c.TaxNum
FROM Accounts A
left join AccountCustomer ac on ac.AccountID = A.AccountID
left join Customers c on c.CustomerNo = ac.CustomerNo
order by A.AccountID;

As we understand, an "AccountID" have multiple customers, so I want to transform tha multiple results to one row, grouping by AccountID (one account belongs to one or many Customers), like the image below:

I tried to use row_number()-expression to get this, but I didn't make it. So my question is, how can I alter my sql-query to get the final result like image above?

View 6 Replies View Related

Transact SQL :: Creating A View Using DISTINCT And Not Getting Unique Results?

Sep 21, 2015

I am building a view to be used to drill down into a Lightswitch app I'm building and to drive this I want to use a view based off the selection of that value several other values will be given to the user to choose from related to the first selection. I've created a view using the following statement:

SELECT DISTINCT TOP (100) PERCENT ARSFamily, ARS_Index
FROM dbo.csr_standards_cmsars
ORDER BY ARSFamily

 but the results come back with ALL the records of the source table (509 rows) when there should have only been 29 rows returned (the appropriate number of families or unique groups).  The index is necessary to have Lightswitch use the view as a data source.what I'm doing wrong here?

View 2 Replies View Related

Transact SQL :: Exporting Stored Procedure Results To Excel

Jun 30, 2015

Goal: To run a stored procedure and export its results to Excel.
Challenge: The stored procedure produces multiple result sets. We want to programmatically export each result set into just 1 Excel file but into different Worksheets. Ex: result set 1 into Worksheet 1, result set 2 into Worksheet 2 and so on. Tools like

BCP utility and OPENROWSET are not enabled for use on the server. So those are out of the league for this one.After I run "EXEC [sp_select_ view_ columns_ from_pp]" -- Within the Results tab of Microsoft SQL Server Management Studio, I see:

viewName columnName columnDataType columnLength column
test test_id varchar 8 0
viewName columnName columnDataType columnLength column
test1 test1_id varchar 8 0
viewName columnName columnDataType columnLength column
test2 test2_id varchar 8 0

As you can see from above, that stored procedure sp_select_view_columns_from_pp is producing multiple result sets within the same Results tab in Microsoft SQL Server Management Studio. We want to make it so it exports to Excel into its own worksheets.

Code:

ALTER PROCEDURE [dbo].[sp_select_view_columns_from_pp]
AS
DECLARE @object_id INT;
DECLARE cur CURSOR FOR SELECT object_id

[code]....

View 7 Replies View Related

Transact SQL :: Insert Constant Value Along With Results Of Select Into Temp Table?

Dec 4, 2015

I'm trying to fill a temp table whose columns are the same as another table plus it has one more column. The temp table's contents are those rows in the other table that meet a particular condition plus another column that is the name of the table that is the source for the rows being added.

Example: 'permTable' has col1 and col2. The data in these two rows plus the name of the table from which it came ('permTable' in this example) are to be added to #temp.

Data in permTable
col1   col2
11,    12
21,     22

Data in #temp after permTable's filtered contents have been added

TableName, col1   col2
permTable, 11,     12
permTable, 21,     22

What is the syntax for an insert like this?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved