Stored Procedure Dbo.SalesByCategory Of Northwind Database: Enter The Query String - Query Attempt Failed. How To Do It Right?
Hi all,
In the Programmability/Stored Procedure of Northwind Database in my SQL Server Management Studio Express (SSMSE), I have the following sql:
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[SalesByCategory] Script Date: 03/25/2008 08:31:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SalesByCategory]
@CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'
AS
IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998'
BEGIN
SELECT @OrdYear = '1998'
END
SELECT ProductName,
TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
FROM [Order Details] OD, Orders O, Products P, Categories C
WHERE OD.OrderID = O.OrderID
AND OD.ProductID = P.ProductID
AND P.CategoryID = C.CategoryID
AND C.CategoryName = @CategoryName
AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
GROUP BY ProductName
ORDER BY ProductName
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
From an ADO.NET 2.0 book, I copied the code of ConnectionPoolingForm to my VB 2005 Express. The following is part of the code:
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Diagnostics
Public Class ConnectionPoolingForm
Dim _ProviderFactory As DbProviderFactory = SqlClientFactory.Instance
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'Force app to be available for SqlClient perf counting
Using cn As New SqlConnection()
End Using
InitializeMinSize()
InitializePerfCounters()
End Sub
Sub InitializeMinSize()
Me.MinimumSize = Me.Size
End Sub
Dim _SelectedConnection As DbConnection = Nothing
Sub lstConnections_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstConnections.SelectedIndexChanged
_SelectedConnection = DirectCast(lstConnections.SelectedItem, DbConnection)
EnableOrDisableButtons(_SelectedConnection)
End Sub
Sub DisableAllButtons()
btnAdd.Enabled = False
btnOpen.Enabled = False
btnQuery.Enabled = False
btnClose.Enabled = False
btnRemove.Enabled = False
btnClearPool.Enabled = False
btnClearAllPools.Enabled = False
End Sub
Sub EnableOrDisableButtons(ByVal cn As DbConnection)
btnAdd.Enabled = True
If cn Is Nothing Then
btnOpen.Enabled = False
btnQuery.Enabled = False
btnClose.Enabled = False
btnRemove.Enabled = False
btnClearPool.Enabled = False
Else
Dim connectionState As ConnectionState = cn.State
btnOpen.Enabled = (connectionState = connectionState.Closed)
btnQuery.Enabled = (connectionState = connectionState.Open)
btnClose.Enabled = btnQuery.Enabled
btnRemove.Enabled = True
If Not (TryCast(cn, SqlConnection) Is Nothing) Then
btnClearPool.Enabled = True
End If
End If
btnClearAllPools.Enabled = True
End Sub
Sub StartWaitUI()
Me.Cursor = Cursors.WaitCursor
DisableAllButtons()
End Sub
Sub EndWaitUI()
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
End Sub
Sub SetStatus(ByVal NewStatus As String)
RefreshPerfCounters()
Me.statusStrip.Items(0).Text = NewStatus
End Sub
Sub btnConnectionString_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnectionString.Click
Dim strConn As String = txtConnectionString.Text
Dim bldr As DbConnectionStringBuilder = _ProviderFactory.CreateConnectionStringBuilder()
Try
bldr.ConnectionString = strConn
Catch ex As Exception
MessageBox.Show(ex.Message, "Invalid connection string for " + bldr.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
Dim dlg As New ConnectionStringBuilderDialog()
If dlg.EditConnectionString(_ProviderFactory, bldr) = System.Windows.Forms.DialogResult.OK Then
txtConnectionString.Text = dlg.ConnectionString
SetStatus("Ready")
Else
SetStatus("Operation cancelled")
End If
End Sub
Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
Dim blnError As Boolean = False
Dim strErrorMessage As String = ""
Dim strErrorCaption As String = "Connection attempt failed"
StartWaitUI()
Try
Dim cn As DbConnection = _ProviderFactory.CreateConnection()
cn.ConnectionString = txtConnectionString.Text
cn.Open()
lstConnections.SelectedIndex = lstConnections.Items.Add(cn)
Catch ex As Exception
blnError = True
strErrorMessage = ex.Message
End Try
EndWaitUI()
If blnError Then
SetStatus(strErrorCaption)
MessageBox.Show(strErrorMessage, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
SetStatus("Connection opened succesfully")
End If
End Sub
Sub btnOpen_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOpen.Click
StartWaitUI()
Try
_SelectedConnection.Open()
EnableOrDisableButtons(_SelectedConnection)
SetStatus("Connection opened succesfully")
EndWaitUI()
Catch ex As Exception
EndWaitUI()
Dim strErrorCaption As String = "Connection attempt failed"
SetStatus(strErrorCaption)
MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Sub btnQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click
Dim queryDialog As New QueryDialog()
If queryDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.Cursor = Cursors.WaitCursor
DisableAllButtons()
Try
Dim cmd As DbCommand = _SelectedConnection.CreateCommand()
cmd.CommandText = queryDialog.txtQuery.Text
Using rdr As DbDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
Dim resultsForm As New QueryResultsForm()
resultsForm.ShowResults(cmd.CommandText, rdr)
SetStatus(String.Format("Query returned {0} row(s)", resultsForm.RowsReturned))
Else
SetStatus(String.Format("Query affected {0} row(s)", rdr.RecordsAffected))
End If
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
End Using
Catch ex As Exception
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
Dim strErrorCaption As String = "Query attempt failed"
SetStatus(strErrorCaption)
MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
SetStatus("Operation cancelled")
End If
End Sub
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I executed the code successfully and I got a box which asked for "Enter the query string".
I typed in the following: EXEC dbo.SalesByCategory @Seafood. I got the following box: Query attempt failed. Must declare the scalar variable "@Seafood". I am learning how to enter the string for the "SQL query programed in the subQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click" (see the code statements listed above). Please help and tell me what I missed and what I should put into the query string to get the information of the "Seafood" category out.
Thanks in advance,
Scott Chang
View Complete Forum Thread with Replies
Sponsored Links:
Related Messages:
RESOLVED RESOLVED An Attempt To Attach An Auto-named Database For File &&<file String&&> Failed &&>&&>&&> But ONLY After SSE Reinstall
RESOLVED RESOLVED RESOLVED DOH! When I rebuilt the OS, I changed the data partition ID's, and didn't remember to change them in the connetion strings Not great, but better than continuing to bang head against wall. Would like to say to MS appreciators that the VS2005 reinstall actually went quite well, considering. =========================================================================== I built an app, works fine. Had the development environment working fine (VS2005 (SP0) and SQL Server Express). It had been stable for months, no problem. Then I had to reinstall XP Pro...(finally threw too many conflicting programs into it, I guess...) I managed to get VS2005 reinstalled ok. However, when I opened and compiled my existing app in VS2005, using Cassini, I got the dreaded error: An attempt to attach an auto-named database for file <file string> failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. I also get this error for the compiled copy of the app on the same machine, running on IIS. (Where it also previously worked fine). The Connection strings are all of the form connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=(specific file string).MDF;Integrated Security=True;User Instance=True" I appreciate that there are zillions of posts on this issue. I'm hoping that someone might know why this should happen in this particular case. The thing that's different about this case is that the app was working fine; I have the app deployed on a demo machine and also on a remote server as well as on the development machine. The only thing that changed is that there was this fresh install of SQL Server Express. I tried using >> sp_configure user instances enabled','1';RECONFIGURE <<< in SSMSEE, which took, but didn't help. So something is different in SSE. Since the app is stable everywhere else, I REALLY don't want to go through and adjust the connection strings...MUCH better to figure out what SSE needs to be happy with the existing connection strings...as it was before. Any suggestions would be appreciated. Thanks! EDIT----TRIED SOME THINGS: Changed folder and file permissions to allow ASPNET full access to the .mdf's and log files (though never had to do this before on the development machine.) No change... Can see the table contents within the .mdf through SSMSE, and also through Server Explorer in VS2005. So because the problem happens with both IIS and Cassini, I'm assuming it's got to be an issue between ASPNET and SSE. EDIT --- TRIED SOME MORE THINGS: I dimly remember that when I had this problem before, it was that the error message was too "dumb". It wasn't my file that had the permissions problems, it was that the SSE System Databases had to have permissions with respect to ASPNET. I tried to set that up but I'm a complete newb on this area, so I don't know if I did it right. In SSMSE I created a Login for MyComputer/ASPNET, and gave it all permissions and roles, and then made it an owner for the four system databases...but no joy. Any pointers on this last piece would be helpful. EDIT - MORE INFO The error details [SqlException (0x80131904): An attempt to attach an auto-named database for file <filestring>.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +739123 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1956 System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +33 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +170 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +349 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +181
View Replies !
View Related
Report Wizard Doesn't Take A Simple Query In The Query String - Query Works In Query Builder When I Supply The Parameters
The following query in the query string: execute p_rpt_cli_v_index_reg_adj_exp_by_bkt2 @as_of_date='06/06/2007', @client_type=3, @index_as_of_date='05/31/2007' produces following error: There is an error in the query, invalid object name '#CLI_1', Invalid object name '#index'. When I open up the query Builder, and provide the same query and run, it asks for those 3 parameters values and after I provide those parameters, the query runs, but, clicking on Ok, produces same error as above in the 'Microsoft Report Designer' information window. The above query works in the Query Analyzer fine. What's so different in the Reporting Services env?
View Replies !
View Related
Stored Procedure Query Optimization - Query TimeOut Error
How to optimize the following Stored procedure running on MSSQL server 2000 sp4 : CREATE PROCEDURE proc1 @Franchise ObjectId , @dtmStart DATETIME , @dtmEnd DATETIME AS BEGIN SET NOCOUNT ON SELECT p.Product , c.Currency , c.Minor , a.ACDef , e.Event , t.Dec , count(1) "Count" , sum(Amount) "Total" FROM tb_Event t JOIN tb_Prod p ON ( t.ProdId = p.ProdId ) JOIN tb_ACDef a ON ( t.ACDefId = a.ACDefId ) JOIN tb_Curr c ON ( t.CurrId = c.CurrId ) JOIN tb_Event e ON ( t.EventId = e.EventId ) JOIN tb_Setl s ON ( s.BUId = t.BUId and s.SetlD = t.SetlD ) WHERE Fran = @Franchise AND t.CDate >= @dtmStart AND t.CDate <= @dtmEnd AND s.Status = 1 GROUP BY p.Product , c.Currency , c.Minor , a.ACDef , e.Event , t.Dec RETURN 1 END GO
View Replies !
View Related
An Attempt To Attach An Auto-named Database For File Failed.
Hi,I recently installed VS Web Developer Express Ediition and SQL Server Express and I'm doing the How To tutorials and I can't finish the basic data access walkthrough:http://msdn2.microsoft.com/en-US/library/tw738475.aspxBecause I get an error like this (link for complete error below): An attempt to attach an auto-named database for file C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData est.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details: System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData est.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.Source Error:An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.http://pastecode.com/6196When I am setting up the data source for the gridview tool, everything works fine and the test query works fine, but then when I try to actually test the output in the browser with Cntrl+F5 I get this error. I have been trying for 48 hours to find a solution on my own. I have googled, I have searched everything and I just am at a point where I think I need to ask someone for help. Please help.
View Replies !
View Related
An Attempt To Attach An Auto-named Database For File Failed
Hi I have a problem when I want to open a page with the database record. This page is created in Visual Web Developer 2005 Express. When I try to open a page I get the following error message even though the connection between the database is ok: An attempt to attach an auto-named database for file C:InetpubwwwrootmembershipApp_Dataaspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:InetpubwwwrootmembershipApp_Dataaspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. I have a computer with Windows XP Professional running IIS 5.1 and ASP.NET 2.0. Also I have SQL Express on my machine. Does any one know how to resolve it.Thanks
View Replies !
View Related
An Attempt To Attach An Auto-named Database For File C:... Failed
Hi, I recently installed VS Web Developer Express Ediition and SQL Server Express and I'm doing the How To tutorials and I can't finish the basic data access walkthrough: http://msdn2.microsoft.com/en-US/library/tw738475.aspx Because I get an error like this (link for complete error below): An attempt to attach an auto-named database for file C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData est.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData est.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. http://pastecode.com/6196 When I am setting up the data source for the gridview tool, everything works fine and the test query works fine, but then when I try to actually test the output in the browser with Cntrl+F5 I get this error. I have been trying for 48 hours to find a solution on my own. I have googled, I have searched everything and I just am at a point where I think I need to ask someone for help. Please help.
View Replies !
View Related
SQL Server DB And Stored Procedure - 1st Attempt
New project and this one going with stored procedures. Should have done it on my first project, but learn as you go... I have the following code to insert info into the database.... SqlCommand myCommand = new SqlCommand("sp_AddOnlineUser", myConnection); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Parameters.Add("@IP_Address", Request.ServerVariables["REMOTE_ADDR"]); myCommand.Parameters.Add("@Session_ID", Session.SessionID.ToString()); myCommand.Parameters.Add("@user_Agent", Request.ServerVariables["HTTP_USER_AGENT"]); myCommand.Parameters.Add("@Referer", Request.ServerVariables["HTTP_REFERER"]); Now, I just want to be sure this stored procedure is correct and if not, suggestions.... create proc dbo.sp_AddOnlineUser @IP_Address char(4), @Session_ID nvarchar(100), @user_Agent nvarchar(255), @Referer nvarchar(255) Thanks all, Zath
View Replies !
View Related
NORTHWIND Database Was Re-created From A Different Database:How Can I Change The Entry In Sysdatabases For Database 'NORTHWIND'?
Hi all, From the http://msdn.microsoft.com/en-us/library/bb384469.aspx (Walkthrough: Creating Stored Procedures for the Northwind Customers Table, I copied the following sql code: --UpdateSPforNWcustomersTable.sql-- USE NORTHWIND GO IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SelectCustomers' AND user_name(uid) = 'dbo') DROP PROCEDURE dbo.[SelectCustomers] GO CREATE PROCEDURE dbo.[SelectCustomers] AS SET NOCOUNT ON; SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM dbo.Customers GO IF EXISTS (SELECT * FROM sysobjects WHERE name = 'InsertCustomers' AND user_name(uid) = 'dbo') DROP PROCEDURE dbo.InsertCustomers GO CREATE PROCEDURE dbo.InsertCustomers ( @CustomerID nchar(5), @CompanyName nvarchar(40), @ContactName nvarchar(30), @ContactTitle nvarchar(30), @Address nvarchar(60), @City nvarchar(15), @Region nvarchar(15), @PostalCode nvarchar(10), @Country nvarchar(15), @Phone nvarchar(24), @Fax nvarchar(24) ) AS SET NOCOUNT OFF; INSERT INTO [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax]) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax); SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (CustomerID = @CustomerID) GO IF EXISTS (SELECT * FROM sysobjects WHERE name = 'UpdateCustomers' AND user_name(uid) = 'dbo') DROP PROCEDURE dbo.UpdateCustomers GO CREATE PROCEDURE dbo.UpdateCustomers ( @CustomerID nchar(5), @CompanyName nvarchar(40), @ContactName nvarchar(30), @ContactTitle nvarchar(30), @Address nvarchar(60), @City nvarchar(15), @Region nvarchar(15), @PostalCode nvarchar(10), @Country nvarchar(15), @Phone nvarchar(24), @Fax nvarchar(24), @Original_CustomerID nchar(5) ) AS SET NOCOUNT OFF; UPDATE [dbo].[Customers] SET [CustomerID] = @CustomerID, [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle, [Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country, [Phone] = @Phone, [Fax] = @Fax WHERE (([CustomerID] = @Original_CustomerID)); SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (CustomerID = @CustomerID) GO ==================================================================================== I executed the above code in my SQL Server Management Studio Express (SSMSE) and I got the following error messages: Msg 911, Level 16, State 1, Line 1 Could not locate entry in sysdatabases for database 'NORTHWIND'. No entry found with that name. Make sure that the name is entered correctly. =============================================================================================================== I know I recreated the NORTHWIND Database from a different Database before and I did not do anything for the entry in sysdatabases. How can I change the entry in sysdatabases for database 'NORTHWIND' now? Please help and advise. Thanks in advance, Scott Chang
View Replies !
View Related
First Attempt At Stored Procedure - Can Anyone Offer Advice
SQL SERVER 2000Hi allThis is my first attempt at writing a stored procedure. I have managed toget it working but its unlikely to be the best way of handling the problem.While writing it I found some things that I don't understand so if any onecould shed any light it would be much appreciated. I have posted these atthe end.Sorry about the length but I thought it might be worthwhile posting the codeThe purpose of the procedures is as follows : we have a view of lots of bitsof information that need automatically mailing to different people. eachelement of information has a name allocated against it. If we had 100 piecesof data, 50 could go to manager 1 25 could go to manager 2 and 25 to manager3 etc...Both SP's look at the same viewThe first SP generates a distinct list of managers and for each managercalls the second SPThe second SP filters the view for the data belonging to the selectedmanager, and builds an HTML mail. It then sends all the bits of informationbelonging to that manager off in an EMAIL to him/her. ( It uses a brilliantbit of code from sqldev.net to handle the mail)the first mail then repeats for all the managers in the listCODE ---- SP 1ALTER PROCEDURE dbo.PR_ADMIN_CLIENT_WEEKLY_NOTIFICATION_2ASbeginSET NOCOUNT ONdeclare @no_of_managers as intdeclare @current_record as intdeclare @manager_name as varchar(100)-- count how many distinct managers we need to send the mail toselect @no_of_managers = COUNT(DISTINCT manager_name) FROMdbo.vw_client_notification_email_1-- open a cursor to the same distinct listdeclare email_list cursor for select distinct manager_name fromdbo.vw_client_notification_email_1 dscopen email_list-- for each distinct manager get the managers name and pass it to the storedprocedure that generates the mail.set @current_record = 0while (@current_record) < @no_of_managersbeginfetch next from email_list into @manager_nameEXECUTE dbo.pr_admin_client_weekly_notification @manager_nameset @current_record = @current_record+1end-- close the cursorclose email_listdeallocate email_listendCODE ---- SP2ALTER PROCEDURE dbo.PR_ADMIN_CLIENT_WEEKLY_NOTIFICATION(@current_manager_name as varchar(100))-- a unique managers name is passed from the calling procedureas beginSET NOCOUNT ON-- declarations for use in the stored procedureDECLARE @to as varchar(100)DECLARE @entry varchar(500)DECLARE @region as varchar(100)DECLARE @type as varchar(100)DECLARE @site_ref as varchar(100)DECLARE @aborted as varchar(100)DECLARE @weblink as varchar(1000)DECLARE @manager_name as varchar(100)DECLARE @manager_email as varchar(100)DECLARE @body VARCHAR(8000)DECLARE @link varchar(150)DECLARE @web_base VARCHAR(150)-- set up a connection to the view that contains the details for the mailDECLARE email_contents cursor for select region,type,site_ref,aborted_visit,link,manager_name,manager_e mail fromvw_client_notification_email_1 where manager_name = @current_manager_nameopen email_contents--some initial textset @body = '<font color="#FF8040"><b>Reports W/E ' +convert(char(50),getdate()) + '</b></font><br><br> <a href = http://xxxx > Click here to logon to xxxxx </a><br><br> '--fetch the first matching record from the table and build the body of themessagefetch next from email_contents into@region,@type,@site_ref,@aborted,@link,@manager_na me,@manager_emailset @web_base = 'http://'set @weblink = @web_base + @linkif @aborted = 0 set @aborted = '' else set @aborted = 'ABORTED'set @body = @body + '<font size="2"><b> Region </b>' + @region+ ' <b>Type</b> ' + @type+ ' <b>Site Reference </b> <a href = "' + @weblink + '">' + @site_ref+'</a>'+ ' <b>Unique Report Reference </b>' + @link + '<br>'-- continue reading the records for this particular message and adding on tothe body of the textwhile(@@fetch_status = 0)beginfetch next from email_contents into@region,@type,@site_ref,@aborted,@link,@manager_na me,@manager_emailif @aborted = 0 set @aborted = '' else set @aborted = 'ABORTED'if (@@fetch_status = 0) set @body = @body + '<b> Region </b>' + @region+ ' <b>Type</b> ' + @type+ ' <b>Site Reference </b> <a href = "' + @weblink + '">' + @site_ref+'</a>'+ '<b>Unique Report Reference </b>' + @link + '<br>'end-- close the cursorset @body = @body + '</font>'close email_contentsdeallocate email_contents-- generate the mailDECLARE @rc int EXEC @rc = master.dbo.xp_smtp_sendmail@FROM = N'FROM ME',@TO = @manager_email,@server = N'server',@subject = N'Weekly Import',@message = @body,@type = N'text/html'endQuestionsis the way I've done it OK. I thought I would be able to do it in a singleSP but I really struggled nesting the cursor things.@@fetchstatus seems to be global, so if your using nested cursors, how doyou know which one you are refering to. If you have multiple calls to thesame SP how does it know which instance of the SP it refers to.When I first wrote it, I used a cursor in SP1 to call SP2, but I couldn'tget the while loop working - I have a feeling it was down to the @@fetchstatus in the 'calling' procedure being overwritten by the@@fetchstatus in the 'called' procedure.The whole @@fetchatus thing seems a bit odd. In the second procedure, I haveto fetch, then check, manipulate then fetch again, meaning that the samemanipulation code is written twice. thats why in the first procedure I usedthe select distint count to know how long the record set is so I only haveto run the manipulation code once. Is what I have done wrong?its possible that the body of the mail could be > 8K, is there anotherdatatype I can use to hold more than 8Kmany thanks for any help or adviceAndy
View Replies !
View Related
Procedure Or Query To Make A Comma-separated String From One Table And Update Another Table's Field With This String.
We have the following two tables : Link ( GroupID int , MemberID int ) Member ( MemberID int , MemberName varchar(50), GroupID varchar(255) ) The Link table contains the records showing which Member is in which Group. One particular Member can be in multiple Groups and also a particular Group may have multiple Members. The Member table contains the Member's ID, Member's Name, and a Group ID field (that will contains comma-separated Groups ID, showing in which Groups the particular Member is in). We have the Link table ready, and the Member table' with first two fields is also ready. What we have to do now is to fill the GroupID field of the Member table, from the Link Table. For instance, Read all the GroupID field from the Link table against a MemberID, make a comma-separated string of the GroupID, then update the GroupID field of the corresponding Member in the Member table. Please help me with a sql query or procedures that will do this job. I am using SQL SERVER 2000.
View Replies !
View Related
Query Analyzer -- Northwind Dbs?
Hi Everyone, I have a question in regards to SQL Server 2000 and its Query Analyzer. I am trying to create certain queries and I need a Northwind database to work with. However, I can't seem to add the database to the dbs' combo box. Basically, I could not find the way to add this database to the analyzer so I can practice with it. Only databases that are there are the system's ones: Master, Model, MSDB and tempdb. So how to add this database to the analyzer's settings? Thanks in advance :)
View Replies !
View Related
An Attempt To Attach An Auto-named Database For File...failed. A Database With The Same Name Exists, Or Specified File Cannot Be
I know allot of folks are having this problem and I tried lots of things but nothing works. I understand the problem is coping the SQL Express on another server is the problem - I just not sure what to do? Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42 This is the last statement on the Stack Trace: SqlException (0x80131904): An attempt to attach an auto-named database for file e:wwwdata81d0493fwwwApp_DataTestDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +735091 I checked my server forum and they said I had to name a database: Example: Database=(unique name); But this didn't work either. I just tried a simple web project that has only one database and one table in SQL Express with one sqldatasource and one datagrid. It works fine on my pc but when I use the copy function in Visio Studio 2005 Pro - I can't run the site on the remote server: www.myjewelrydirect.com I tried coping the database manually. I tried disconnecting the database before I copy it. Below is my connection statement: <connectionStrings> <add name="TestDB" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|TestDatabase.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> </connectionStrings> With all the comments in these forums - this must be a bug. I have been working on this problem for over 2 weeks - HELP!
View Replies !
View Related
Query About Employees Table In Northwind DB
Dear all, Please run this query in northwind DB. SELECT Employees.EmployeeID, Employees.LastName, Employees.FirstName, Employees.ReportsTo, 'REPORTS TO', Employees_1.LastName, Employees_1.FirstName FROM Employees LEFT OUTER JOIN Employees Employees_1 ON Employees.ReportsTo = Employees_1.EmployeeID The results are, EmployeeID LastName FirstName ReportsTo LastName FirstName ----------- -------------------- ---------- ----------- ---------- --------- ----------- ---------- 1 Davolio Nancy 2 REPORTS TO Fuller Andrew 2 Fuller Andrew NULL REPORTS TO NULL NULL 3 Leverling Janet 2 REPORTS TO Fuller Andrew 4 Peacock Margaret 2 REPORTS TO Fuller Andrew 5 Buchanan Steven 2 REPORTS TO Fuller Andrew 6 Suyama Michael 5 REPORTS TO Buchanan Steven 7 King Robert 5 REPORTS TO Buchanan Steven 8 Callahan Laura 2 REPORTS TO Fuller Andrew 9 Dodsworth Anne 5 REPORTS TO Buchanan Steven for employeeID 6,7 and 9 I need o/p as 6 Suyama Michael 5 REPORTS TO Buchanan Steven REPORTS TO Andrew Fuller ie. Find out all the information of all the superiors. for Employee ID 6 superior is 5 and for empolyeeID 5 is 2 and soon, The search should goon till there are no more superiors. Thanks, Holy. P.S : Sorry! I reposted again just to have with a better example
View Replies !
View Related
Calling Stored Procedures From ADO.NET-VB 2005 Express:1)Compile Errors && Warnings,2)Northwind Database In Database Explorer?
Hi all, I try to learn "How to Access Stored Procedures with ADO.NET 2.0 - VB 2005 Express: (1) Handling the Input and Output Parameters and (2) Reporting their Values in VB Forms". I found a good article "Calling Stored Procedures from ADO.NET" by John Paul Cook in http://www.dbzine.com/sql/sql-artices/cook6. I downloaded the source code into my VB 2005 Express: Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Public Class Form_Cook Inherits System.Windows.Form.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents labelPAF As System.Windows.Forms.Label Friend WithEvents labelNbrPrices As System.Windows.Forms.Label Friend WithEvents UpdatePrices As System.Windows.Forms.Button Friend WithEvents textBoxPAF As System.Windows.Forms.TextBox Friend WithEvents TenMostExpensive As System.Windows.Forms.Button Friend WithEvents grdNorthwind As System.Windows.Forms.DataGrid Friend WithEvents groupBox2 As System.Windows.Forms.GroupBox <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.labelPAF = New System.Windows.Forms.Label() Me.labelNbrPrices = New System.Windows.Forms.Label() Me.textBoxPAF = New System.Windows.Forms.TextBox() Me.UpdatePrices = New System.Windows.Forms.Button() Me.groupBox2 = New System.Windows.Forms.GroupBox() Me.TenMostExpensive = New System.Windows.Forms.Button() Me.grdNorthwind = New System.Windows.Forms.DataGrid() Me.GroupBox1.SuspendLayout() Me.groupBox2.SuspendLayout() CType(Me.grdNorthwind, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'GroupBox1 ' Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control() {Me.labelPAF, Me.labelNbrPrices, Me.textBoxPAF, Me.UpdatePrices}) Me.GroupBox1.Location = New System.Drawing.Point(8, 8) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(240, 112) Me.GroupBox1.TabIndex = 9 Me.GroupBox1.TabStop = False ' 'labelPAF ' Me.labelPAF.Location = New System.Drawing.Point(8, 16) Me.labelPAF.Name = "labelPAF" Me.labelPAF.Size = New System.Drawing.Size(112, 32) Me.labelPAF.TabIndex = 2 Me.labelPAF.Text = "Enter Price Adjustment Factor" ' 'labelNbrPrices ' Me.labelNbrPrices.Location = New System.Drawing.Point(8, 80) Me.labelNbrPrices.Name = "labelNbrPrices" Me.labelNbrPrices.Size = New System.Drawing.Size(216, 16) Me.labelNbrPrices.TabIndex = 5 ' 'textBoxPAF ' Me.textBoxPAF.Location = New System.Drawing.Point(120, 16) Me.textBoxPAF.Name = "textBoxPAF" Me.textBoxPAF.TabIndex = 0 Me.textBoxPAF.Text = "" ' 'UpdatePrices ' Me.UpdatePrices.Location = New System.Drawing.Point(8, 48) Me.UpdatePrices.Name = "UpdatePrices" Me.UpdatePrices.Size = New System.Drawing.Size(88, 23) Me.UpdatePrices.TabIndex = 6 Me.UpdatePrices.Text = "Update Prices" ' 'groupBox2 ' Me.groupBox2.Controls.AddRange(New System.Windows.Forms.Control() {Me.TenMostExpensive, Me.grdNorthwind}) <Part 1----To be continued due to the length of this post>
View Replies !
View Related
To DB/SQL Teachers: A Wrong Query On Northwind DB Discussion
Good day to all. I'm a DB teacher in a University. Planning and developing SQL exercises for my students I found a "tricky" or extrange sql exercise. The sql exercise using Northwind DB reads as follows: "Wich is the total amount of the freight that corresponds to all orders containing products of seafood category ?" The first sql code that comes to my mind was: select sum(freight) from orders o, "order details" d, products p, categories c where o.orderid=d.orderid and d.productid=p.productid and p.categoryid=c.categoryid and categoryname='seafood' This is equivalent code constructed with Query constructor in Enterprise Manager: SELECT SUM(dbo.Orders.Freight) AS Expr1 FROM dbo.Orders INNER JOIN dbo.[Order Details] ON dbo.Orders.OrderID = dbo.[Order Details].OrderID INNER JOIN dbo.Products ON dbo.[Order Details].ProductID = dbo.Products.ProductID INNER JOIN dbo.Categories ON dbo.Products.CategoryID = dbo.Categories.CategoryID WHERE (dbo.Categories.CategoryName = N'seafood') These 2 equivalent queries output 27722.9600 as result, but the correct result (total freight) is 23791.1400. Did you also think (as I did) that the exposed code is correct? Now I know the correct sql code that gives the corect answer and also the explanation why the code exposed fails, but before share it under your posible request, want to know your tech comments about this exercise in order to know if this particular exercise is "tricky" (make people to fail) or is my total fault and need to review my strategies of applying/constructing sql (and teaching). Thanks a lot. Carlos
View Replies !
View Related
Stored Proc Error By Northwind Database
i try create this example:http://www.codeproject.com/KB/webforms/ReportViewer.aspxI have Northwind database added in the SQL server management and i select Northwind databse in drop box and I push Execute!ALTER PROCEDURE ShowProductByCategory(@CategoryName nvarchar(15) )ASSELECT Categories.CategoryName, Products.ProductName, Products.UnitPrice, Products.UnitsInStockFROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryIDWHERE CategoryName=@CategoryNameRETURNbut error is:Msg 208, Level 16, State 6, Procedure ShowProductByCategory, Line 11Invalid object name 'ShowProductByCategory'.on web not so clear what is issue pls. help
View Replies !
View Related
Building A Query In A Stored Proc With String
This should be an easy enough answer to find if I just knew what to search on! I am building a query within my stored procedure based on what parameters are passed in. For example, suppose I have a table with first name and last name. I can call the sp with either first name or last name or both, so I build a query accordingly that says: select * from tblNames where FirstName = 'Hannah' or select * from tblNames where LastName = 'Montana' or select * from tblNames where FirstName = 'Hannah' and LastName='Montana' My problem is putting the single quotes around the variable value. SELECT @whereClause = @whereClause + ' AND tblNames.LastName=' @LastName-with-singlequotes-around-it Thanks
View Replies !
View Related
Ad Hoc Query Vs Stored Procedure Performance Vs DTS Execution Of Stored Procedure
Has anyone encountered cases in which a proc executed by DTS has the following behavior: 1) underperforms the same proc when executed in DTS as opposed to SQL Server Managemet Studio 2) underperforms an ad-hoc version of the same query (UPDATE) executed in SQL Server Managemet Studio What could explain this? Obviously, All three scenarios are executed against the same database and hit the exact same tables and indices. Query plans show that one step, a Clustered Index Seek, consumes most of the resources (57%) and for that the estimated rows = 1 and actual rows is 10 of 1000's time higher. (~ 23000). The DTS execution effectively never finishes even after many hours (10+) The Stored procedure execution will finish in 6 minutes (executed after the update ad-hoc query) The Update ad-hoc query will finish in 2 minutes
View Replies !
View Related
Stored Procedure In Query Analyzer Vs Linked Procedure In MS Access
For some reason, I run a stored procedure in Query Analyzer and it works fine. When I run the very same procedure in MS access by clicking on its link I have to run it twice. The first run gives me the message that the stored procedure ran correctly but returned no records. The second run gives me the correct number of records but I have to run it twice. I am running month-to-month data. The first run is Jan thru March. Jan and Feb have no records so I run three months on the first set. The ensuing runs are individual months from April onward. The output is correct but any ideas on why I have to do it twice in Access? I am a bit new to stored procedures but my supervisor assures me that it should be exactly the same. ddave
View Replies !
View Related
Using A Stored Procedure To Query Other Stored Procedures And Then Return The Results
Seems like I'm stealing all the threads here, : But I need to learn :) I have a StoredProcedure that needs to return values that other StoredProcedures return.Rather than have my DataAccess layer access the DB multiple times, I would like to call One stored Procedure, and have that stored procedure call the others to get the information I need. I think this way would be more efficient than accessing the DB multiple times. One of my SP is:SELECT I.ItemDetailID, I.ItemDetailStatusID, I.ItemDetailTypeID, I.Archived, I.Expired, I.ExpireDate, I.Deleted, S.Name AS 'StatusName', S.ItemDetailStatusID, S.InProgress as 'StatusInProgress', S.Color AS 'StatusColor',T.[Name] AS 'TypeName', T.Prefix, T.Name AS 'ItemDetailTypeName', T.ItemDetailTypeID FROM [Item].ItemDetails I INNER JOIN Item.ItemDetailStatus S ON I.ItemDetailStatusID = S.ItemDetailStatusID INNER JOIN [Item].ItemDetailTypes T ON I.ItemDetailTypeID = T.ItemDetailTypeID However, I already have StoredProcedures that return the exact same data from the ItemDetailStatus table and ItemDetailTypes table.Would it be better to do it above, and have more code to change when a new column/field is added, or more checks, or do something like:(This is not propper SQL) SELECT I.ItemDetailID, I.ItemDetailStatusID, I.ItemDetailTypeID, I.Archived, I.Expired, I.ExpireDate, I.Deleted, EXEC [Item].ItemDetailStatusInfo I.ItemDetailStatusID, EXEC [Item].ItemDetailTypeInfo I.ItemDetailTypeID FROM [Item].ItemDetails IOr something like that... Any thoughts?
View Replies !
View Related
How To Use A Url Query String Value To Access A Database Record With The Same Value.
Ok, to start I will say I am a novice so detailed solutions are much appreciated. I believe I am on the right track. Here is what I am trying to accomplish. I have a page that uses an xml driven google map. When you click on the map marker, the info bubble displays brief information about a community and a link specified from the xml file. I have specified the links in the xml file to pass a query string variable ex: /community.aspx?name=uniqueCommunityNameHere. I tested this by simply placing a label on the community.aspx page that restated the "name" value - works fine (first commented out line of Page_Load). Now I need to complete my VB function that pulls the data record from the database - based on the parameter input from the query string - when the page loads. So if the user clicks the link on the marker for community1, it will populate community.aspx with info about community1 from the database... if they click community7 it will display that community info etc. Data Table: "Community" Data Fields: ID, Name, Description, Address, City, State, Phone, SalesRep. ASPX Page Design Elements: lblID, lblName, lblDesc, lblAddress.... etc. Here is my start... I will need help with the sql statement for sure - how do I create a where clause from the query string parameter passed in? Thanks so much for your help! Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load'My initial test to see that the query string is working lblName.Text = Request("name").ToString() ' Get the community info when loading community.aspx for the user selected communityIf Not IsPostBack ThenLoadCommunityInfo(Request("name").ToString())End IfEnd SubPrivate Sub LoadCommunityInfo(ByVal community)' Define data objectsDim conn As SqlConnectionDim comm As SqlCommandDim reader As SqlDataReader ' Read the connection string from Web.configDim connectionString As String = ConfigurationManager.ConnectionStrings("CONHTConnectionString").ConnectionString' Initialize connectionconn = New SqlConnection(connectionString)' Create commandcomm = New SqlCommand("SELECT * FROM Community WHERE Name = " & community, conn)' Enclose database code in Try-Catch-FinallyTry' Open the connectionconn.Open()' Execute the commandreader = comm.ExecuteReader()' Populate the list of community information -> Make the labels.text = the database fields --> lblName.text = table-Community field-"Name"lblName.Text = "Name"lblDesc.Text = "Description"....' Close the readerreader.Close()Catch' Display error messagedbErrorLabel.Text = "Error loading the community information!<br />"Finally' Close the connectionconn.Close()End TryEnd Sub
View Replies !
View Related
The Merge Process Failed To Execute A Query Because The Query Timed Out
Hi there. I have occasional sincronization error.-XSUBSYSTEM Merge -XSERVER MYSERVER -XCMDLINE 0 -XCancelEventHandle 000006E0 2006-12-22 14:55:00.833 Connecting to Subscriber 'Subscriber01' 2006-12-22 14:55:00.895 Connecting to Distributor 'Publisher01' 2006-12-22 14:55:02.974 Initializing 2006-12-22 14:55:03.083 Connecting to Publisher 'Publisher01' 2006-12-22 14:55:06.005 Retrieving publication information 2006-12-22 14:55:06.130 Retrieving subscription information. 2006-12-22 15:00:07.222 The merge process failed to execute a query because the query timed out. If this failure continues, increase the query timeout for the process. When troubleshooting, restart the synchronization with verbose history logging and specify an output file to which to write. 2006-12-22 15:00:07.456 Error converting data type nvarchar to numeric. 2006-12-22 15:00:07.800 Category:SQLSERVER Source: Subscriber01 Number: 8114 Message: Error converting data type nvarchar to numeric. After manual syncronization it goes under control. Could anybody explain the relationship between converting error and timed out query? If this is poor connection's problem how can I increase the query timeout for the process?
View Replies !
View Related
User-defined Stored Procedures &&"InsertCustomer&&"in Northwind Database That Is Cached In Database Explorer:No New Values Inserted?
Hi all, I put "Northwind" Database in the Database Explorer of my VB 2005 Express and I have created the following stored procedure in the Database Exploror: --User-defined stored procedure 'InsertCustomer'-- ALTER PROCEDURE dbo.InsertCustomer ( @CustomerID nchar(5), @CompanyName nvarchar(40), @ContactName nvarchar(30), @ContactTitle nvarchar(30), @Address nvarchar(60), @City nvarchar(15), @Region nvarchar(15), @PostalCode nvarchar(10), @Country nvarchar(15), @Phone nvarchar(24), @Fax nvarchar(24) ) AS INSERT INTO Customers ( CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax ) VALUES ( @CustomerID, @CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax ) ================================================= In my VB 2005 Express, I created a project "KimmelCallNWspWithAdoNet" that had the following code: --Form_Kimmel.vb-- Imports System.Data Imports System.Data.SqlClient Imports System.Data.SqlTypes Public Class Form_Kimmel Public Sub InsertCustomer() Dim connectionString As String = "Integrated Security-SSPI;Persist Security Info=False;" + _ "Initial Catalog=northwind;Data Source=NAB-WK-EN12345" Dim connection As SqlConnection = New SqlConnection(connectionString) connection.Open() Try Dim command As SqlCommand = New SqlCommand("InsertCustomer", connection) command.CommandType = CommandType.StoredProcedure command.Parameters.Add("@CustomerID", "PAULK") command.Parameters.Add("@CompanyName", "Pauly's Bar") command.Parameters.Add("@ContactName", "Paul Kimmel") command.Parameters.Add("@ContactTitle", "The Fat Man") command.Parameters.Add("@Address", "31025 La Jolla") command.Parameters.Add("@City", "Inglewoog") command.Parameters.Add("@Region", "CA") command.Parameters.Add("@Counrty", "USA") command.Parameters.Add("@PostalCode", "90425") command.Parameters.Add("@Phone", "(415) 555-1234") command.Parameters.Add("@Fax", "(415 555-1235") Console.WriteLine("Row inserted: " + _ command.ExecuteNonQuery().ToString) Catch ex As Exception Console.WriteLine(ex.Message) Throw Finally connection.Close() End Try End Sub End Class ============================================== I executed the Form_Kimmel.vb and I got no errors. But I did not get the new values insterted in the table "Custermers" of Northwind database. Please help and tell me what I did wrong and how to correct this problem. Thanks in advance, Scott Chang
View Replies !
View Related
Need Stored Procedure For This Query
Hi,I am weak in writing stored procedure and want to learn it step by step.Now I have written a query and the requirement is such that I need to convert it in stored procedure.query:Select distinct empskill.tcatid,Coalesce(prm,0) as prm,coalesce(secn,0) as secn,a as technology,coalesce(skd,0) as skd,coalesce(knd,0) as knd,coalesce(tnd,0)as tnd,coalesce(dnd,0) as dnd from empskill RIGHT OUTER JOIN (select tcatid,Count(skilltypeid) AS prm from empskill where skilltypeid=1 group by tcatid) prms ON empskill.tcatid=prms.tcatid LEFT OUTER JOIN (select tcatid,Count(skilltypeid) AS secn from empskill where skilltypeid=2 group by tcatid) secs on empskill.tcatid=secs.tcatid RIGHT OUTER JOIN (select technology.category as a,empskill.tcatid from empskill,technology where empskill.tcatid=technology.tcatid group by empskill.tcatid,technology.category ) s ON empskill.tcatid=s.tcatid LEFT OUTER JOIN (select tcatid,Count(skilllevelid) AS skd from empskill where skilllevelid=1 group by tcatid) skds on empskill.tcatid=skds.tcatid LEFT OUTER JOIN (select tcatid,Count(skilllevelid) AS knd from empskill where skilllevelid=2 group by tcatid) knds on empskill.tcatid=knds.tcatid LEFT OUTER JOIN (select tcatid,Count(skilllevelid) AS tnd from empskill where skilllevelid=3 group by tcatid) tnds on empskill.tcatid=tnds.tcatid LEFT OUTER JOIN (select tcatid,Count(skilllevelid) AS dnd from empskill where skilllevelid=4 group by tcatid) dnds on empskill.tcatid=dnds.tcatid union select top 1 500 as tcatid,'' as prm,'' as sec,'more' as technology,'' as skd,'' as knd,'' as tnd,'' as dnd from empskill Can you please explain step by step how to convert this to stored procedure.Thanks a lot
View Replies !
View Related
Stored Procedure Query
hey.. say i have a table with 4 columns, Id, col1, col2 & col 3the way it works is the id and one of the col's will have info, the other 2 cols will be emptyim trying to write a proc that returns the value of the column that has info + a number that is stored in a string to represent the column eg: CREATE PROCEDURE proc_Test @Id int, @Answer varchar(100) outputasset nocount on select @Answer = col1 +', 1'from myTablewhere Id= @Idif @@rowcount < 1select @Answer = col2 +', 2'from myTablewhere Id= @Idif @@rowcount < 1 select @Answer = col3 +', 3' from myTable where Id= @IdreturnGO but for some reason, it only process's the first select statment and if nothing is in the column, it returns - ', 1' cheers!!!
View Replies !
View Related
Using A Stored Procedure As A Sub Query
Is there any way to do the following?select Max(FieldOne) From (spGetSomeData 100,'test' )Or do I need to define a view and have the stored proc use that view?The stored proc does some things with temp tables that would bedifficult to replicate with a view which is why I'm asking.
View Replies !
View Related
Help With A Stored Procedure/query?
I did a join on two tables to get the following results. I saved theresults in a #temptable.idtable2idtable2descripdateinserted================================================== ==13descrip111/3/200224descrip211/2/200233descrip111/4/200143descrip110/5/200354descrip212/8/200165descrip39/10/2002I want to query that #temptable to get the max date for each table2idand only return those record. So I need a query to get the followresults...idtable2idtable2descripdateinserted================================================== ==24descrip211/2/200243descrip110/5/200365descrip39/10/2002Question...What query can I make with #temptable to give me the results?
View Replies !
View Related
Need Help With Query Or Possible Stored Procedure
I need some help with the following query:DECLARE @SRV VARCHAR(20), @date smalldatetimeSET @SRV = (select @@servername)SET @date = '20040901'select Srv_Name = @SRV, DB_Name = 'DB_NAME', Table_Name ='Info_Table', Date_of_Records = @date,count(*) AS 'Actual Total' ,max (SER_NO)- min (SER_NO)+1 AS 'Desired total ',count(*) - (max (SER_NO)- min (SER_NO)+1) AS 'Missing Records',min (SER_NO) AS 'MIN SER_NO',max (SER_NO) AS 'MAX SER_NO'from Info_Tablewhere DateTime >= @date and DateTime < dateadd(DAY, 1, @date)I would like to get records of next 30 days from the @date. I can copypaste this query 30 times with different date and get the desiredresults but would prefer to use one query only.If possible would like a add a variable to get the table name by usingthe following query into the above query:SELECT DISTINCT so.nameFROM sysobjects AS soINNER JOIN syscolumns AS scON so.id=sc.idWHERE so.name like 'm_%' AND sc.name = 'DateTime' OR sc.name ='SER_NO'So basic idea is to run one simple (or complexed) query to get 30 daysdata of many tables select by the above query.Can someone help please?
View Replies !
View Related
Run A Stored Procedure From A Query?
I want to run a stored procedure from a query... can I do this? Thanks! CREATE VIEW dbo.V_EmploymentTerminationsResignations AS --the next 3 lines produce errors... declare @StartDate datetime declare @EndDate datetime exec [hrs2].[dbo].[sp_getquarterinfo] --@StartDate OUTPUT, @EndDate OUTPUT --they're designed to replace the hard coded stuff in the WHERE statement... --a snippet of the originl view... SELECT TOP 100 PERCENT dbo.Employee.OrgID, dbo.Employee.SSN, dbo.Employee.EMPLOYEE_NAME, , dbo.Employee.SPECIAL_STATUS, WHERE ... (dbo.Employee.LAST_PERS_ACTN_DATE BETWEEN CONVERT(DATETIME, '2001-07-01 00:00:00', 102) AND CONVERT(DATETIME, '2001-10-01 00:00:00', 102)) ORDER BY dbo.Employee.LAST_PERS_...
View Replies !
View Related
Stored Procedure In A Query
In access, I can create a function that I can call in a query. It runs that function iteratively. Do I have the same ability with SQL server? Can I call a stored procedure WITHIN a query? I would like to be able to do something like: Insert into tblOrders(spFirst_Name) Select {Call spUpperLower(tblClients.First_Name)} from tblClients Where ... So basically, spUpperLower would run on every First Name Row in the result set. Any help would be much appreciated. Thanks, Brad
View Replies !
View Related
Query To Stored Procedure
Hi, I have created an SQL query which returns the expected data. However, when I try to run it as a stored procedure, I get no rows returned. (I assume I running the procedure correctly e.g. exec getNonDeployed RCN20047) Code: CREATE PROCEDURE getNonDeployed @packageID text AS BEGIN DECLARE @CollectionID VARCHAR(10) DECLARE @Collections TABLE (CollectionID VARCHAR(10)) set @CollectionID = (SELECT CollectionID from ProgramOffers where OfferID='@packageID'); WITH CollectionFull (SubCollectionID) AS ( -- Create the anchor query. This establishes the starting -- point SELECT SubCollectionID from v_CollectToSubCollect a where a.SubCollectionID=@CollectionID UNION ALL -- Create the recursive query. This query will be executed -- until it returns no more rows select a.SubCollectionID from v_CollectToSubCollect a inner join CollectionFull b on b.SubCollectionID=a.ParentCollectionID ) Insert Into @Collections SELECT * FROM CollectionFull select a.RuleName AS MACHINENAME, c.IPAddress0 as IPADDRESS from v_CollectionRuleDirect a inner join @Collections b on b.CollectionID=a.CollectionID inner join v_GS_DEVICE_NETWORK c on c.ResourceID=a.ResourceID where RuleName not in (select distinct a.MachineName as MACHINENAME from v_StatusMessage a, v_StatMsgAttributes b, v_CollectionRuleDirect c, v_GS_DEVICE_NETWORK d, v_Collection e where (a.RecordID=b.RecordID AND a.MachineName=c.RuleName and c.ResourceID=d.ResourceID and c.CollectionID=e.CollectionID) AND b.AttributeValue IN ('@packageID')) END
View Replies !
View Related
Help With Stored Procedure Or Query
Hello All I need help on a query or stored procedure in my C# app what i need to do is make a report to our fisheries service every three months the totals of each species of fish every fishermen catchs. eg Fishermen1 Species1 100Kg Species2 200Kg and so on I can get the results using a select query one at a time using parameters FishermenId,SpeciesId and StartDate and EndDate but with over a 100 species it will take forever to do is there a way i can fill a dataset with the results using the FishermensID and start and end date as the parameters and get the totals for all the species that fishermen has court.I have not got reporting services i want to show the results in a datagridview and i can print it out from there. My tables are Fishermen Table1 FishermenID int FishermenName vchar Details Table2 DetailsID int FishermenID int SpeciesID int SpeciesName vchar Quantity nchar Date smalldatetime Species Table3 SpeciesID int SpeciesName vchar SpeciesCode vchar Hope someone can help Thanks Barry
View Replies !
View Related
Stored Procedure Vs. Query
Hi, is it better to use stored procedures or queries in terms of performance? I'm running application in ASP.NET, now the amount of data in the database is not very high, but I expect it'll grow, so I wonder about speed of queries etc. Is it better to use SELECT ... FROM ... or to prepare stored procedure for such select? What about insert/update/delete? thanks Jiri Matejka
View Replies !
View Related
Query In Stored Procedure
Hi All: I have a situation where Im calling a stored procedure to insert some information. When this information is inserted it is given a date/time stamp - say something in Aug. There will be some corresponding records from the previous month already in the database that have some additional information that was manually added. I need to query the corresponding records from the previous month and insert that info into the records that were just inserted. the problem Im having is that i need to grab the most recent corresponding record. could be a day or a month prior to the one I just inserted. the also could be a record for months prior to that. So how do i get the most recent corresponding record to my inserted record Any suggestion on how to query this? and then pass the result to an udpate statement
View Replies !
View Related
Database Mail Problem...Query Execution Failed: Error Initializing COM
Hello - I'm having a problem sending the query set as an email text attachment. Test transmissions from Database mail working fine. Send simple messages with the sp_send_dbmail sproc works fine as well. It is only when I try and send a query result that things blow up. The query itself is working fine also, so I'm now down to think there is some esoteric problem with the sproc itself. Surface config features have database mail on, and SQL Mail off. Anyone know the solution to this? Thanks in advance! Actual SQL ... use epic go EXEC msdb.dbo.sp_send_dbmail @profile_name = 'SQLMail', @recipients = 'rvolters@whaleyfoodservice.com', @body = 'Testing sqlmail with sproc.', @subject = 'Orders with invalid tech numbers', @query = 'SELECT order_no, order_ext, line_no from epic..STG_BNERPT_INVALIDTECHNOS' , @attach_query_result_as_file = 1 ; Message Results... Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 476 Query execution failed: Error initializing COM Msg 0, Level 11, State 0, Line 0 A severe error occurred on the current command. The results, if any, should be discarded. Investigating the sproc itself shows... Line 476 in the sproc is the beginning of a 'trap' --Raise an error it the query execution fails -- This will only be the case when @append_query_error is set to 0 (false) IF( (@RetErrorMsg IS NOT NULL) AND (@exclude_query_output=0) ) BEGIN RAISERROR(14661, -1, -1, @RetErrorMsg) END RETURN (@rc) this is the last section of code in the sproc
View Replies !
View Related
Dynamic Query In Stored Procedure
Hi, I have a table with values such as test1, test2, test3, test4, test5. I need to write a stored procedure with paramater (number TINYINT, number2 TINYINT), the number represents the field that I'm going to select and compare. For example if I pass in (1,5) I will need the fields test1 and test5 and store them in Temp and Temp2. How do I write the following to so it will dynamically select which field to use when passing the parameters? DECLARE @Temp TINYINT, DECLARE @Temp2 TINYINT, SELECT top 1 Temp = test1, Temp2 = test5 from table
View Replies !
View Related
Run Dynamic Query Using Stored Procedure
Hi, I need to create a stored procedure, which needs to accept the column name and table name as input parameter, and form the select query at the run time with the given column name and table name.. my procedure is, CREATE PROC spTest @myColumn varchar(100) , @myTable varchar(100) AS SELECT @myColumn FROM @myTable GO This one showing me the error, stating that myTable is not declared.. .............as i need to perform this type of query for more than 10 tables.. i need the stored procedure to accept the column and table as parameters.. Plese help me?? Is it possible in stored procedure..
View Replies !
View Related
Dynamic Query In Stored Procedure
Hi i am trying to make the "userName" section of the code below dynamic as well, how can i do this, the reason being userName will not always be passed through to it. ALTER PROCEDURE [dbo].[stream_UserFind] ( @userName varchar(100), @subCategoryID INT, @regionID INT )ASdeclare @StaticStr nvarchar(5000)set @StaticStr = 'SELECT DISTINCT SubCategories.subCategoryID, SubCategories.subCategoryName,Users.userName ,UserSubCategories.userIDFROM Users INNER JOIN UserSubCategories ON Users.userID= UserSubCategories.userIDINNER JOINSubCategories ON UserSubCategories.subCategoryID = SubCategories.subCategoryID WHERE UserName like ' + char(39) + '%' + @UserName + '%' + char(39) if(@subCategoryID <> 0) set @StaticStr = @StaticStr + ' and SubCategories.subCategoryID = ' + cast( @subCategoryID as varchar(10))if(@regionID <> 0) set @StaticStr = @StaticStr + ' and SubCategories.RegionId = ' + cast( @regionID as varchar(10)) print @StaticStr exec(@StaticStr) )
View Replies !
View Related
Paging Query Without Using Stored Procedure
Hello, my table is clustered according to the date. Has anyone found an efficient way to page through 16 million rows of data? The query that I have takes waaaay too long. It is really fast when I page through information at the beginning but when someone tries to access the 9,000th page sometimes it has a timeout error. I am using sql server 2005 let me know if you have any ideas. Thanks I am also thinking about switch datavase software to something that can handle that many rows. Let me know if you have a suggestion on a particular software that can handle paging through 16 million rows of data.
View Replies !
View Related
Query ProductID In Stored Procedure
I have created a Stored Procedure:SELECT ID, Productname, Price, Desc, img_urlFROM ProductsWHERE (ID = [ -- Products.aspx?ID=x -- ])Question: I want to view the product details for that ID in QueryString on my ASP.Net page www.myhomepage.com/Product.aspx?ID=2. How do I?...Using:FormView1SqlDataSourceVB/ASP.Net 2005 & SQL Server 2005 Express.
View Replies !
View Related
Stored Procedure That Will Only Run In Query Analyzer.
Hi all, I have a problem with a stored procedure that executes properly when running it in Query Analyzer. When I call the SP from an ASP.NET application, it doesn't seem to run properly. I have verified that the parameter values are correct, but there is one update command that does not update any rows when it executes although it should. I tried stepping through the SP from within Visual Studio and it still does not work properly even though all parameters have the correct values. Why would a SP execute properly when used in QA but not when an application executes it?
View Replies !
View Related
Stored Procedure And Query Plans Different
I have a stored procedure that suddenly started performing horribly.The query plan didn't look right to me, so I copy/pasted the code andran it (it's a single SELECT statement). That ran pretty well and useda query plan that made sense. Now, I know what you're all thinking...stored procedures have to optimize for variable parameters, etc.Here's what I've tried to fix the issue:1. Recompiled the stored procedure2. Created a new, but identical stored procedure3. Created the stored procedure with the RECOMPILE option4. Created the stored procedure with a hard-coded value instead ofaparameter5. Changed the stored procedure to use dynamic SQLIn every case, performance did not improve and the query plan remainedthe same (I could not easily confirm this with the dynamic SQLversion, but performance was still horrible).I am currently running UPDATE STATISTICS on all of the involvedtables, but that will take awhile.Any ideas?Thanks!-Tom.
View Replies !
View Related
Insert Query With Stored Procedure
Hi,is it possible to create an "INSERT INTO ..... "Select from storedprocedure" Query?I want to create an temporary table. In this table I want to enter the data,which I can get from an stored procedure.But in the FROM-clause a stored procedure is not allowed?
View Replies !
View Related
Stored Procedure Query Question.
ok, i have the following query which runs as a stored proc... ALTER PROCEDURE [dbo].[sp_SelectDocumentBySearch] @searchString varchar(255) AS BEGIN SELECT document_id, document_code, document_title, document_category_id, document_description, document_date_added, document_date_revision, document_last_revised, document_author, document_version, document_level, category_id, category_title FROM tbl_documents JOIN tbl_categories ON document_category_id = category_id WHERE document_level = '3' AND document_code LIKE @searchString OR document_title LIKE @searchString OR document_description LIKE @searchString OR category_title LIKE @searchString END in my .net app, its a search function, u make the @searchString parameter to be %string% (as a search feature to find anything with 'string')...now, when there is a string present, it works correctly by displaying results only with document_level = '3'....however, when there is no string, that is just a %% as the @searchString, it returns all results, regardless of what document_level is... but i want to keep it for a wildcard search, yet still retain document_level = '3' statement. is this possible? Cheers, Justin
View Replies !
View Related
Stored Procedure To Run Query And Then Insert
I have a query that select rows from the employees,salary_head and salary_group tables this is the query SELECT dbo.salary_head.salary_group_id, dbo.salary_group.salary_group, dbo.salary_head.amount, dbo.grade_level.[level], dbo.employees.employ_name, dbo.employees.work_id, dbo.employees.company_id, dbo.employees.designation, dbo.salary_head.level_id, dbo.employees.terminate, dbo.employees.banks_id, dbo.employees.bank_account_no FROM dbo.employees INNER JOIN dbo.salary_head INNER JOIN dbo.salary_group ON dbo.salary_head.salary_group_id = dbo.salary_group.salary_group_id ON dbo.employees.level_id = dbo.salary_head.level_id INNER JOIN dbo.grade_level ON dbo.employees.level_id = dbo.grade_level.level_id i also have a table called payrollers1 with the following fields payroll_id int auto payperiod_id int employee_id level_id designation_id banks_id bankaccount_no salarygroup_id Amount I am trying to write a stored procedure that will run the above query and then insert the values of the employee_id,level_id,designation_id,salary_group_i d,amount rows into the payroller table. As for the payperiod_id i want the Stored procedure to look up the max payperiod value. I am totally new to stored procedure and do not know how to write this code. Can somebody help me with this code.
View Replies !
View Related
|