Is It Possible To Execute The T-Sql Code Of Common Table Expressions In VB 2005 Express?

Jan 2, 2008

Hi all,
I have the following T-SQL code of Common Table Express (CTE) that works in the SQL Server Management Studio Express (SSMSE):

--CTE.sql--

USE ChemAveRpd

GO

WITH PivotedLabTests AS

(

SELECT LT.AnalyteName, LT.Unit,

Prim = MIN(CASE S.SampleType WHEN 'Primary' THEN LT.Result END),

Dupl = MIN(CASE S.SampleType WHEN 'Duplicate' THEN LT.Result END),

QA = MIN(CASE S.SampleType WHEN 'QA' THEN LT.Result END)

FROM LabTests LT

JOIN Samples S ON LT.SampleID = S.SampleID

GROUP BY LT.AnalyteName, LT.Unit

)

SELECT AnalyteName, Unit, avg1 = (abs(Prim + Dupl)) / 2,

avg2 = (abs(Prim + QA)) / 2,

avg3 = (abs(Dupl + QA)) / 2,

RPD1 = (abs(Prim - Dupl) / abs(Prim + Dupl)) * 2,

RPD2 = (abs(Prim - QA) / abs(Prim + QA)) * 2,

RPD3 = (abs(Dupl - QA) / abs(Dupl + QA)) * 2

FROM PivotedLabTests

GO

===========================================
How can I execute this set of the CTE.sql code in the VB 2005 Express via the Stored Procedure programming?

Please help and respond.

Thanks in advance,
Scott Chang

View 1 Replies


ADVERTISEMENT

Common Table Expressions

Aug 31, 2006

Hi guys,

I know its not a good idea to give you a big query...but/...

I have a query (given below) with Common table expressions. It is giving me error : The multi-part identifier "dbo.tmpValidServices_ALL.Service" could not be bound. for all the fields .. Do you have any idea.. I fed up with analysing query.. made me mad.. please help me...

 

----------------------------------------------

DECLARE @sql nvarchar(MAX), @paramlist nvarchar(4000)

SET @sql = 'WITH Q1 (SiteID,Programme,Complete,PID,COC,NotionalSum,TVMinsSUM,Postcode,Suburb,Qty)
AS

(SELECT
 dbo.tmpValidServices_ALL.SiteID,
 dbo.tmpValidServices_ALL.Programme,
 dbo.tmpValidServices_ALL.Complete AS Complete,
 dbo.tmpValidServices_ALL.RID AS PID,
 dbo.tmpValidServices_ALL.COC# AS COC,
 (dbo.lkpService.Notional$) AS NotionalSum,
 (TVMins) AS TVMinsSUM,
 dbo.tmpDemographics_ALL.Postcode,
 dbo.tmpdemographics_ALL.Suburb,
                count(*) as Qty

FROM  lkpService

INNER JOIN dbo.tmpValidServices_ALL vs  ON dbo.lkpservice.code = dbo.tmpValidServices_ALL.Service
INNER JOIN dbo.tmpDemographics_ALL ON dbo.tmpValidServices_ALL.RID = dbo.tmpDemographics_ALL.RID '

IF @COCGroup IS NOT NULL
SELECT     @sql = @sql + 'LEFT OUTER JOIN dbo.lkpCOC c ON dbo.tmpValidServices_ALL.COC = c.pvcode '

SELECT     @sql = @sql + 'LEFT OUTER JOIN dbo.lkpAgency ag ON vs.SiteID = ag.EXACT# '      

SELECT     @sql = @sql + 'WHERE dbo.lkpService.Schedule = @Schedule '

 IF @StartDate IS NOT NULL
     SELECT     @sql = @sql + ' AND (dbo.tmpValidServices_ALL.Complete  >= @StartDate ) '

 IF @EndDate IS NOT NULL
      SELECT     @sql = @sql + ' AND (dbo.tmpValidServices_ALL.Complete <= @EndDate ) '


 IF @SiteID IS NOT NULL
       SELECT     @sql = @sql + 'AND (ag.EXACT# = @SiteID) '

 IF @COCGroup IS NOT NULL
 SELECT     @sql = @sql + ' AND (c.pvcode = @COCGroup OR c.pvcode IN (SELECT COC FROM lkpCOCGroup WHERE COCGroup = @COCGroup)) '

 IF @Provider IS NOT NULL
 SELECT     @sql = @sql + 'AND (dbo.tmpValidServices_ALL.Provider = @Provider) '

 IF @Postcode IS NOT NULL
SELECT     @sql = @sql + 'AND (dbo.tmpdemographics_ALL.Postcode = @Postcode) '

SELECT     @sql = @sql  + ' GROUP BY dbo.tmpValidServices_ALL.SiteID,
                                                              dbo.tmpValidServices_ALL.Programme,
                                                              dbo.tmpValidServices_ALL.Complete ,
                                                              dbo.tmpValidServices_ALL.RID , 
                                                              dbo.tmpValidServices_ALL.COC# ,
                                                              dbo.tmpDemographics_ALL.postcode, 
                                                              dbo.tmpdemographics_ALL.Suburb,
                                                              (dbo.lkpService.Notional$),
                                                              (dbo.lkpService.TVMins)  ) 

SELECT COUNT(DISTINCT PID + CAST(Complete AS varchar(20))  + CAST(COC AS varchar(20)) + CAST(SiteID AS varchar(20)) + CAST(Programme AS varchar(20))) AS Visits,
 COUNT(DISTINCT PID + CAST(SiteID AS varchar(20)) + CAST(Programme AS varchar(20))) AS Patients, 
 COUNT(DISTINCT  CAST(COC AS varchar(20)) + CAST(SiteID AS varchar(20)) + CAST(Programme AS varchar(20)) + CAST(PID AS varchar(20))) AS COCs,
 SUM(NotionalSum) AS NotionalSum,
 SUM(TVMinsSUM) AS TVMinsSUM,Postcode,Suburb,sum(Qty) as Qty
 
FROM Q1

Group by Postcode,Suburb

Order by Postcode,Suburb  '

SET              @paramlist = '@SiteID as numeric,
@COCGroup as varchar(20),
@Postcode as varchar(20),
@StartDate DateTime,
@EndDate DateTime,
@Schedule varchar(20),
@Provider varchar(20)'
                     
 EXEC sp_executesql @sql, @paramlist, @SiteID, @COCGroup, @Postcode, @StartDate, @EndDate, @Schedule, @Provider

View 2 Replies View Related

Distinct In Common Table Expressions CTE

Feb 20, 2007

I have managed to write my first CTE SQL that handles recursion but I have a problem with distinct - can't get that to work!!
My CTE:WITH StudentsHierarchy(SystemID1, GroupID, AccessType, AccessGroupID, StudentID, HierarchyLevel) AS
(
--Base Case
SELECT
SystemID,
GroupID,
AccessType,
AccessGroupID,
StudentID,
1 as HierarchyLevel
FROM UserGroup a

UNION ALL

--Recursive step
SELECT
u.SystemID,
u.GroupID,
u.AccessType,
u.AccessGroupID,
u.StudentID,
uh.HierarchyLevel + 1 as HierarchyLevel
FROM UserGroup u
INNER JOIN StudentsHierarchy uh ON
u.GroupID = uh.AccessGroupID

)
Select sh.SystemID1, sh.GroupID, sh.AccessType, sh.AccessGroupID, sh.StudentID, sh.HierarchyLevel, (select StudentName from Student s
where sh.StudentID = s.StudentID) AS StudentName from StudentsHierarchy sh
WHERE AccessType = 'S'
 
and I would like to have a distinct on the StudentID like:Select DISTINCT sh.StudentID, sh.SystemID1, sh.GroupID, sh.AccessType, sh.AccessGroupID, sh.StudentID, sh.HierarchyLevel, (select StudentName from Student s
where sh.StudentID = s.StudentID) AS StudentName from StudentsHierarchy sh
WHERE AccessType = 'S'
 
 
How should I do?
 

View 1 Replies View Related

Microsoft OLE DB Provider For IBM DB2 Does Not Accept Common Table Expressions

Oct 26, 2007



After reading all the comments about microsoft ole db provider for db2, I've started converting a project from ibm db2 provider to microsoft ole db provider, for the reason that the server would not need a ibm client software installation anylonger.
However in one of the dataflows there is a select statement on the DB2 database (AS400 iseries DB2 V5R4) that uses common table expression. The Oledb data source in the Dataflow returns zero input columns when I use the microsoft provider instead of the ibm provider. When I set it back to use the ibm oledb provider the input columns are available again.
The common table expression is used in the select statement like:
WITH x AS (SELECT ... FROM mytable WHERE ...)
SELECT x.*, (x.a - x.b) As diff
FROM x

We are not allowed to change anything in the DB2 database, so using views or sprocs is not an option.

Did anyone else experience this and can it be avoided without changing the selct logic?

View 3 Replies View Related

Common Table Expressions With Table Creation

May 20, 2008

I have multiple Common Table Expressions i.e CTE1,CTE2,...CTE5.

I want to Create Temperory Table and inserting data from CTE5. Is this possible to create?

like:


create table #temp (row_no int identity (1,1),time datetime, action varchar(5))

insert into #temp select * from cte5

View 4 Replies View Related

Syntax Of Operators And Common Functions In Expressions

Apr 4, 2008

Hi all, real basic question:
I can't seem to find a basic reference that tells me the syntax and allowable values of parameters in common functions such as Format or CDate when editing a Field Expression in Visual Studio (Report Definition Language?). Where would I start?

For example, I've discovered that the Format function "Returns a string formatted according to instructions contained in a format String expression.", and the string expression can have values like "D" and "d" which produce different results, but where would I find out what the allowable string expressions are and their meaning?

I have also been guessing at the syntax of the CDate command with no luck. I need a reference that tells me what the different function parameters mean.

thanks
Jac

View 1 Replies View Related

Common Table Expression (CTE):How To Delete A Wrong CTE That Is In SQL Server Management Studio Express (SSMSE)?

Feb 25, 2008

Hi all,

I ran the following CTE sql code:


Use ChemDatabase

GO

WITH PivotedTestResults AS

(

SELECT TR.AnalyteName, TR.Unit,

Prim = MIN(CASE S.SampleType WHEN 'Primary' THEN TR.Result END),

Dupl = MIN(CASE S.SampleType WHEN 'Duplicate' THEN TR.Result END),

QA = MIN(CASE S.SampleType WHEN 'QA' THEN TR.Result END)

FROM TestResults TR

JOIN Samples S ON TR.SampleID = S.SampleID

GROUP BY TR.AnalyteName, TR.Unit

)

SELECT AnalyteName, UnitForConc,

avg1 = abs(Prim + Dupl) / 2,

avg2 = abs(Prim + QA) / 2,

avg3 = abs(Dupl + QA) / 2,

RPD1 = abs(Prim - Dupl) / abs(Prim + Dupl) * 2,

RPD2 = abs(Prim - QA) / abs(Prim + QA) * 2,

RPD2 = abs(Dupl - QA) / abs(Dupl + QA) * 2

FROM PivotedTestResults

GO

//////////////////////////////////////////////////////////////////////////////////////
I got the following errors:

Msg 207, Level 16, State 1, Line 9

Invalid column name 'Unit'.

Msg 207, Level 16, State 1, Line 3

Invalid column name 'Unit'.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

I guess that I had "Unit" (instead of "UnitForConc"), when I executed the sql code last time!!!???
How can I delete the old, wrong CTE that is already in the ChemDatabase of my SSMSE?

Please help and advise.

Thanks in advance,
Scott Chang

View 5 Replies View Related

SQL Server 2005 Common Table Expression(CTE) Implement Reg.

Aug 30, 2006

Hi,

We are developing the web application using ASP.NET 2.0 using C# with Backend of SQL Server 2005.

Now we have one requirement with my client, Already our application live in ASP using MS Access Database. In Access Database our client already wrote the query, those query call the another query from same database. So I want to over take this functionality in SQL Server 2005.

In ASP Application, We call this query €œ081Stats€? from Record set.

This €˜081Stats€™ query call below sub query itself

Master Query: 081Stats

SELECT DISTINCTROW [08Applicants].school, [08Applicants].Applicants, [08Interviewed].Interviewed, [Interviewed]/[Applicants] AS [interviewed%], [08Accepted].Accepted, [Accepted]/[Applicants] AS [Accepted%], [08Dinged].Dinged, [Dinged]/[Applicants] AS [Dinged%], [08Waitlisted].Waitlisted, [Applicants]-[Accepted]-[Dinged] AS Alive, [08Matriculating].Matriculating, [Matriculating]/[Accepted] AS [Yield%]
FROM ((((08Applicants LEFT JOIN 08Interviewed ON [08Applicants].school = [08Interviewed].school) LEFT JOIN 08Accepted ON [08Applicants].school = [08Accepted].school) LEFT JOIN 08Dinged ON [08Applicants].school = [08Dinged].school) LEFT JOIN 08Waitlisted ON [08Applicants].school = [08Waitlisted].school) LEFT JOIN 08Matriculating ON [08Applicants].school = [08Matriculating].school;

Sub Query 1: 08Accepted

SELECT statusTbl.school, Count(1) AS Accepted
FROM statusTbl
WHERE (((statusTbl.decision)=1) AND ((statusTbl.yearapp)="2008"))
GROUP BY statusTbl.school
ORDER BY Count(1) DESC;

Sub Query 2: 08Applicants

SELECT statusTbl.school, Count(1) AS Accepted
FROM statusTbl
WHERE (((statusTbl.decision)=1) AND ((statusTbl.yearapp)="2008"))
GROUP BY statusTbl.school
ORDER BY Count(1) DESC;

Sub Query 3: 08Dinged

SELECT statusTbl.school, Count(1) AS Dinged
FROM statusTbl
WHERE (((statusTbl.decision)=0) AND ((statusTbl.yearapp)="2008"))
GROUP BY statusTbl.school
ORDER BY Count(1) DESC;

Sub Query 4: 08Interviewed

SELECT statusTbl.school, Count(1) AS Interviewed
FROM statusTbl
WHERE (((statusTbl.interview)=True) AND ((statusTbl.yearapp)="2008"))
GROUP BY statusTbl.school
ORDER BY Count(1) DESC;

Sub Query 5: 08Matriculating

SELECT statusTbl.school, Count(1) AS Matriculating
FROM statusTbl
WHERE (((statusTbl.userdec)=True) AND ((statusTbl.yearapp)="2008"))
GROUP BY statusTbl.school
ORDER BY Count(1) DESC;

So now I got the solution from SQL Server 2005. I.e. Common Table Expressions, So I got the syntax and other functionality, Now my doubts is how do implement the CTE in SQL Server 2005, where can I store the CTE in SQL Server 2005.

How can I call that CTE from ASP.NET 2.0 using C#?

CTE is replacing the Stored Procedure and Views, because it is memory based object in SQL Server 2005.

How can I implement the CTE, where can I write the CTE and where can I store the CTE.

And how can I call the CTE from ASP.NET 2.0 using C#.

It€™s Very Urgent Requirements.

We need your timely help.

With Thanks & Regards,
Sundar

View 1 Replies View Related

Expressions And Other Code?

Jun 16, 2007

Is there any way to write C# code in SQL Server Reporting Services?

View 1 Replies View Related

Insert Images In SQL 2005 Express DB, Using C# Code For Asp.net 2.0 (VS 2005)

Aug 31, 2006

Help!

I found about a dozen samples and articles in the net about inserting images in a sql database, but they were either using VB, or asp only or SQL 2000 and although I tried them all, none worked...
Can you help me by posting some code on how to insert images in SQL 2005, using C# in Visual Studio 2005 (asp.net 2.0)

Thanks.

View 11 Replies View Related

Cannot Open SQL Server 2005 Express From C#.Net 2005 (using Code)

Mar 15, 2008


can anybody help me.

I am getting an sql Server 2005 connection error from c#.net 2005.

following is the error
--------------------------------------------------------------------------------------------

{"An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}

---------------------------------------------------------------------------------------------


i have changed the default settings. local and remote connection are enabled.

following are the code i am using in C# .Net 2005
---------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


SqlConnection conn = new SqlConnection("server=localhost; user id= sa; pwd =; Initial Catalog=testdb;");

---------------------------------------------------------------------------------------------------------------


when i connect through the c# wizard, everything is perfect.

thanks in advance
sam alex

View 10 Replies View Related

Join Returns More Than One Row, Post Code Regular Expressions

Mar 23, 2006

Hi,I trying to write a select statement that will return each of my salesmen a region code based on a table of post codes using wildcards... eg.MK1 1AA would be matched in the region code table to MK1%SELECT dn.DEALER_CODE, dn.NAME AS DNAME, rc.REGION_ID,rc.POST_CODE, dn.POSTAL_CODEFROM REGIONAL_CODES rc CROSS JOINDEALER_NAW dnWHERE (dn.POSTAL_CODE LIKE rc.POST_CODE)The above statement works BUT there are some post code areas such asour friends in Milton Keynes that are split into two regions... eg MK1is region id 2 and MK10 is region 3.So a dealer with post code MK10 1AA would be matched to both rowsreturning duplicatesPOST_CODE REGION_IDMK1% 2MK10% 3I think the answer would lie in a subquery which returns the ID of theregion with the longest length of the postcode match (e.g.len(POST_CODE) for the rc table... return only the MAX....any ideas????Any help muchos appreciated, and I apologies now for the naming of thedealers name as a reserve word... not me!Ct

View 2 Replies View Related

Looking For A Way To Refer To A Package Variable Within Any Transact-SQL Code Included In Execute SQL Or Execute T-SQL Task

Apr 19, 2007

I'm looking for a way to refer to a package variable within any
Transact-SQL code included in either an Execute SQL or Execute T-SQL
task. If this can be done, I need to know the technique to use -
whether it's something similar to a parameter placeholder question
mark or something else.


FYI - I've been able to successfully execute Transact-SQL statements
within the Execute SQL task, so I don't think the Execute T-SQL task
is even necessary for this purpose.

View 5 Replies View Related

Connect To Sql Express 2005 Through Code

Feb 1, 2007

Hi All:

I'm new to using sql express 2005 as the database, so I apologize if my question is very basic.

I can connect to db through sql mngmt studio, but I don't know how to connect through application code. The authentication mode is windows. I'm having trouble with the provider in the application code.

Can someone please tell me where I can find more detailed information on available providers for sql express?

Thanks for any help, as I'm against a tight deadline.

View 6 Replies View Related

How To Use SQL Svr 2005 Express In Excel 2003 VBA Code?

Jun 23, 2006

Hello,

how can I use SQL Svr 2005 Express as database engine in background through VBA code in Excel 2003?

I want to CREATE and DELETE tables and SELECT, INSERT and UPDATE data. Is it possible to use ADO or other database objects to get in contact with SQL Svr 2005 Express?

Thanks a lot.

Christian

View 4 Replies View Related

Finding SQL 2005 Standard Edition Code Which Will Break In Express

Feb 11, 2008

Hi,

We're currently developing an application against SQL Server 2005 Standard Edition. Recently, we've started to consider deploying certain installations against SQL Server Express. We're particularly worried about some stored procedures we've written taking advantages of features which will not be available in SQL Server Express, is there a simple compliance tool or such that we can scan our existing tables/functions/stored procedures/etc with to identify potential pitfalls when running on SQL Server Express?

Thanks,
Jeremy

View 4 Replies View Related

Replacing Tables In SQL Express By An Updated Table Of The Same Name Through VB2008 Code

Apr 17, 2008

Hello,

I have an application written in Visual Basic 2008, using a SQL Express 2008 database. This application runs in several locations on stand-alone PC's and there is no network connecting them.
I have to maintain a SQL database in a central location an would like to be able to distribute updated tables from that central location by using an USB stick and replace the tables of the same name in the different locations with the updated ones on my USB stick.
This I would like to do using code within my VB2008 application.

Can someone please help me on the way to achieve this. Is it possible to give some concrete code examples, as I am a newbie as a SQL Server user.

Many thanks and greetings,

Michel


View 5 Replies View Related

Common SQL Server Express Problem That I Can't Seem To Solve

Jul 9, 2006

Hi Guys,
[VS2005, .NET 2.0 SQL Server Express]
I could really use some help with this one - as in desperately!:
I have a couple of database projects which run fine in Debug Mode from VS2005, but I can't get them to run outside of it.
The problem is that, for some reason, the login to the database file isn't succeeding.  I'm getting the following errors:

.NET Project: System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
DotNetNuke 4.0.3 Project: ERROR: Could not connect to database specified in connectionString for SqlDataProvider.  (I sometimes get a "The Server Version does not match the Database Version" error)
Here are my connection strings for the above two scenarios:
<connectionStrings>     <add name="EpgDbConnection" connectionString="Data              Source=.SQLEXPRESS;AttachDbFilename=C:ProjectsEpgEpg.mdf;Integrated              Security=True;Connect Timeout=30;User Instance=True"              providerName="System.Data.SqlClient" /></connectionStrings>
<connectionStrings>      <add name="SiteSqlServer" connectionString="Data Source=.SQLExpress;Integrated              Security=True;User Instance=True;AttachDBFilename=|DataDirectory|Database.mdf;"              providerName="System.Data.SqlClient" /></connectionStrings>
My assumption is that I need to switch from Integrated Security (is that Windows Security?) to SQL Server Security, but I'm battling to do that effectively.
A pointer to a simple step-by-step guide would be fantastic, but, if there isn't such a thing available, I have a number of specific questions:
Question 1: Why does one need to switch from Integrated Security to SQL Server Security?
If I'm right, I suspect that my connection strings will become:
 <connectionStrings>  <add name="SiteSqlServer" connectionString="Data Source=     (local);user id=gary;password=password;Connect Timeout=30" />
and
 <connectionStrings>  <add name="EpgDbConnection" connectionString="Data Source=(local);     user id=gary;password=password;Connect Timeout=30" />
respectively.
Question 2: Are these strings correct?
(I receive a login failed error)
Question 3: How do I go about changing the Security Setting, using either VS2005 or SQL Server?
(I've modified permissions at a SQL Server Express level from Windows Authentication mode to SQL Server and Windows Authentication mode in SSMS, but the Authentication Method can't seem to be changed at the database file level. View connection string (under database properties), reveals an unalterable "Windows Authentication" Authentication Method.)
Question 4: I've managed to add a user and password at the SQL Server Express level.  What roles should the user have?
I'd be very grateful for any help you could give me.  I've tried everything I can find or think of and am not getting anywhere!
Thanks very much.
Regards
Gary

View 2 Replies View Related

Microsoft SQL Server 2005 Express Edition Service Pack 2 Error Code: 0x2B22

May 19, 2007

Hi i tried to install the Microsoft SQL Server 2005 Express Edition Service Pack 2 but was unable to do so. I got an error message saying: Error Code: 0x2B22



I went through what the message said, but i was unable to solve the problem. Below is the summary of the problem. Please help me solve it.



Time: 05/19/2007 12:32:24.781
KB Number: KB921896
Machine: DET-NB0631262
OS Version: Microsoft Windows XP Professional Service Pack 2 (Build 2600)
Package Language: 1033 (ENU)
Package Platform: x86
Package SP Level: 2
Package Version: 3042
Command-line parameters specified:
/quiet
/allinstances
Cluster Installation: No

**********************************************************************************
Prerequisites Check & Status
SQLSupport: Passed

**********************************************************************************
Products Detected Language Level Patch Level Platform Edition
Express Database Services (SQLEXPRESS) ENU RTM 2005.090.1399.00 x86 EXPRESS
Express Database Services (SQLExpress) ENU SP2 x86 EXPRESS

**********************************************************************************
Products Disqualified & Reason
Product Reason
Express Database Services (SQLEXPRESS) Unable to start service

**********************************************************************************
Processes Locking Files
Process Name Feature Type User Name PID

**********************************************************************************
Product Installation Status
Product : Express Database Services (SQLEXPRESS)
Product Version (Previous): 1399
Product Version (Final) :
Status : Not Applied
Log File :
SQL Express Features : SQL_Data_Files,SQL_Engine,SQL_Replication,SQL_SharedTools
Error Number : 11042
Error Description : Unable to start service
----------------------------------------------------------------------------------
Product : Express Database Services (SQLExpress)
Product Version (Previous):
Product Version (Final) :
Status : Not Applied
Log File :
SQL Express Features : Client_Components,Connectivity,SDK
Error Number : 0
Error Description :
----------------------------------------------------------------------------------

**********************************************************************************
Summary
Unable to start service
Exit Code Returned: 11042

View 3 Replies View Related

Problems Deploying Express Database App In Common App Data Path

Jan 28, 2008

Hello,
I would like to deploy a per-machine Express database as part of my VS2005 C# desktop application. The deployment must work with both XP and Vista from the same setup files. I'm not using One-Click installation. I don't want my users to have to configure Express with the Surface Area Configuration tool.

Since the database cannot go in C:Program Files because of Vista ACL issues, I am using COMMONAPPDATACompanyNameAppName as the install path for the database and other user writable application files. In XP this expands to C:Documents and SettingsAll UsersApplication DataCompanyNameAppName and in Vista it is C:ProgramDataCompanyNameAppName. Neither of these paths have write privileges for unprivileged users, so the install program needs to change the write permissions at install time. Right now I am using SetACL ( http://setacl.sourceforge.net/ ), to do that and the install goes fine with write permissions on the companyName folder and it's children for all users.

But I can't connect to the mdf file in my COMMONAPPDATACompanyNameAppName folder. If I am the administrator/installer it works fine, but as an unprivileged user I get different errors, but mostly "Could not login user ...". For debugging, I have also tried installing the database in the "AppFolder" directory (which for my app in both Vista and XP is C:Program FilesCompanyNameAppName) and using "User Instance=true" in the connection string, and the connection is made but (at least on XP) the unprivileged user cannot write to the database because the folder lacks write privileges for that user.

I suppose one thing I could do would be to change the folder/file permissions in the AppFolder, but I am reluctant to do that because I have read that Microsoft does not guarantee that the "Compatibility" feature in Vista for the Program Files directory will be available in future releases/service packs.

So is there a way to do a simple installation/db connection for a per-machine database located in a COMMONAPPDATA path?

Thanks for your help.

View 13 Replies View Related

Creating A Common Table Expression--temporary Table--using TSQL???

Jul 23, 2005

Using SQL against a DB2 table the 'with' key word is used todynamically create a temporary table with an SQL statement that isretained for the duration of that SQL statement.What is the equivalent to the SQL 'with' using TSQL? If there is notone, what is the TSQL solution to creating a temporary table that isassociated with an SQL statement? Examples would be appreciated.Thank you!!

View 11 Replies View Related

T-SQL And Visual Basic 2005 Codes That Execute A User-Defined Stored Procedure In Management Studio Express (Part 2)

Jan 23, 2008

Hi Jonathan Kehayias, Thanks for your valuable response.

I had a hard time to sumbit my reply in that original thread yesterday. So I created this new thread.

Here is my response to the last code/instruction you gave me:

I corrected a small mistake (on Integrated Security-SSPI and executed the last code you gave me.

I got the following debug error message:

1) A Box appeared and said: String or binary data would be truncated.

The statement has been terminated.

|OK|

2) After I clicked on the |OK| button, the following message appeared:

This "SqlException was unhandled

String or binary data would be truncated.

The statement has been terminated."

is pointing to the "Throw" code statement in the middle of

.......................................

Catch ex As Exception

MessageBox.Show(ex.Message)

Throw

Finally

..........

Please help and advise how to correct this problem in my project that is executed in my VB 2005 Express-SQL Server Management Studio Express PC.



Thanks,
Scott Chang

The code of my Form1.vb is listed below:

Imports System.Data

Imports System.Data.SqlClient

Imports System.Data.SqlTypes

Public Class Form1

Public Sub InsertNewFriend()

Dim connectionString As String = "Data Source=.SQLEXPRESS;Initial Catalog=shcDB;Integrated Security=SSPI;"

Dim connection As SqlConnection = New SqlConnection(connectionString)

Try

connection.Open()

Dim command As SqlCommand = New SqlCommand("sp_insertNewRecord", connection)

command.CommandType = CommandType.StoredProcedure

command.Parameters.Add("@procPersonID", SqlDbType.Int).Value = 7

command.Parameters.Add("@procFirstName", SqlDbType.NVarChar).Value = "Craig"

command.Parameters.Add("@procLastName", SqlDbType.NVarChar).Value = "Utley"

command.Parameters.Add("@procAddress", SqlDbType.NVarChar).Value = "5577 Baltimore Ave"

command.Parameters.Add("@procCity", SqlDbType.NVarChar).Value = "Ellicott City"

command.Parameters.Add("@procState", SqlDbType.NVarChar).Value = "MD"

command.Parameters.Add("@procZipCode", SqlDbType.NVarChar).Value = "21045"

command.Parameters.Add("@procEmail", SqlDbType.NVarChar).Value = "CraigUtley@yahoo.com"

Dim resulting As String = command.ExecuteNonQuery

MessageBox.Show("Row inserted: " + resulting)

Catch ex As Exception

MessageBox.Show(ex.Message)

Throw

Finally

connection.Close()

End Try

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

InsertNewFriend()

End Sub

End Class

View 6 Replies View Related

Valid Expressions Are Constants, Constant Expressions, And (in Some Contexts) Variables. Column Names Are Not Permitted.

Dec 11, 2007

I want to have this query insert a bunch of XML but i get this error...


Msg 128, Level 15, State 1, Procedure InsertTimeCard, Line 117

The name "ExpenseRptID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

Msg 128, Level 15, State 1, Procedure InsertTimeCard, Line 151

The name "DateWorked" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

What am i doing wrong...Can anyone help me out!! Thanks!!

p.s I know this query looks crazy...


Code Block

IF EXISTS (SELECT NAME FROM sysobjects WHERE NAME = 'InsertTimeCard' AND type = 'P' AND uid=(Select uid from sysusers where name=current_user))
BEGIN
DROP PROCEDURE InsertTimeCard
END
go
/*********************************************************************************************************
** PROC NAME : InsertTimeCardHoursWorked
**
** AUTHOR : Demetrius Powers
**
** TODO/ISSUES
** ------------------------------------------------------------------------------------
**
**
** MODIFICATIONS
** ------------------------------------------------------------------------------------
** Name Date Comment
** ------------------------------------------------------------------------------------
** Powers 12/11/2007 -Initial Creation
*********************************************************************************************************/
CREATE PROCEDURE InsertTimeCard
@DateCreated DateTime,
@EmployeeID int,
@DateEntered DateTime,
@SerializedXML text,
@Result int output
as
declare @NewTimeCardID int
select @NewTimeCardID = max(TimeCardID) from OPS_TimeCards
-- proc settings
SET NOCOUNT ON

-- local variables
DECLARE @intDoc int
DECLARE @bolOpen bit
SET @bolOpen = 0
--Prepare the XML document to be loaded
EXEC sp_xml_preparedocument @intDoc OUTPUT, @SerializedXML
-- check for error
IF @@ERROR <> 0
GOTO ErrorHandler
--The document was prepared so set the boolean indicator so we know to close it if an error occurs.
SET @bolOpen = 1


--Create temp variable to store values inthe XML document
DECLARE @tempXMLTimeCardExpense TABLE
(
TimeCardExpenseID int not null identity(1,1),
TimeCardID int,
ExpenseRptID int,
ExpenseDate datetime,
ProjectID int,
ExpenseDescription nvarchar(510),
ExpenseAmount money,
ExpenseCodeID int,
AttachedRct bit,
SubmittoExpRep bit
)
DECLARE @tempXMLTimeCardWorked TABLE
(
TimeCardDetailID int not null identity(1,1),
TimeCardID int,
DateWorked DateTime,
ProjectID int,
WorkDescription nvarchar(510),
BillableHours float,
BillingRate money,
WorkCodeID int,
Location nvarchar(50)
)
-- begin trans
BEGIN TRANSACTION
insert OPS_TimeCards(NewTimeCardID, DateCreated, EmployeeID, DateEntered, Paid)
values (@NewTimeCardID, @DateCreated, @EmployeeID, @DateEntered, 0)
-- check for error
IF @@ERROR <> 0
GOTO ErrorHandler


--Now use @intDoc with XPATH style queries on the XML
INSERT @tempXMLTimeCardExpense (TimeCardID, ExpenseRptID, ExpenseDate, ProjectID, ExpenseDescription, ExpenseAmount, ExpenseCodeID, AttachedRct, SubmittoExpRep)
SELECT @NewTimeCardID, ExpenseRptID, ExpenseDate, ProjectID, ExpenseDescription, ExpenseAmount, ExpenseCodeID, AttachedRct, SubmittoExpRep
FROM OPENXML(@intDoc, '/ArrayOfTimeCardExpense/TimeCardExpense', 2)
WITH ( ExpenseRptID int 'ExpenseRptID',
ExpenseDate datetime 'ExpenseDate',
ProjectID int 'ProjectID',
ExpenseDescription nvarchar(510) 'ExpenseDescription',
ExpenseAmount money 'ExpenseAmount',
ExpenseCodeID int 'ExpenseCodeID',
AttachedRct bit 'AttachedRct',
SubmittoExpRep bit 'SubmittoExpRep')
-- check for error
IF @@ERROR <> 0
GOTO ErrorHandler

-- remove XML doc from memory
EXEC sp_xml_removedocument @intDoc
SET @bolOpen = 0


INSERT OPS_TimeCardExpenses(TimeCardID, ExpenseRptID, ExpenseDate, ProjectID, ExpenseDescription, ExpenseAmount, ExpenseCodeID, AttachedRct, SubmittoExpRep)
Values(@NewTimeCardID, ExpenseRptID, ExpenseDate, ProjectID, ExpenseDescription, ExpenseAmount, ExpenseCodeID, AttachedRct, SubmittoExpRep)
select @NewTimeCardID, ExpenseRptID, ExpenseDate, ProjectID, ExpenseDescription, ExpenseAmount, ExpenseCodeID, AttachedRct, SubmittoExpRep
from @tempXMLTimeCardExpense
-- check for error
IF @@ERROR <> 0
GOTO ErrorHandler

-- For time worked...
INSERT @tempXMLTimeCardWorked(TimeCardID, DateWorked, ProjectID, WorkDescription, BillableHours, BillingRate, WorkCodeID, Location)
SELECT @NewTimeCardID, DateWorked, ProjectID, WorkDescription, BilliableHours, BillingRate, WorkCodeID, Location
FROM OPENXML(@intDoc, '/ArrayOfTimeCardWorked/TimeCardWorked', 2)
WITH ( DateWorked DateTime 'DateWorked',
ProjectID datetime 'ProjectID',
WorkDescription nvarchar(max) 'WorkDescription',
BilliableHours float 'BilliableHours',
BillingRate money 'BillingRate',
WorkCodeID int 'WorkCodeID',
Location nvarchar(50)'Location')
-- check for error
IF @@ERROR <> 0
GOTO ErrorHandler

-- remove XML doc from memory
EXEC sp_xml_removedocument @intDoc
SET @bolOpen = 0


INSERT OPS_TimeCardHours(TimeCardID, DateWorked, ProjectID, WorkDescription, BillableHours, BillingRate, WorkCodeID, Location)
Values(@NewTimeCardID,DateWorked, ProjectID, WorkDescription, BillableHours, BillingRate, WorkCodeID, Location)
select @NewTimeCardID ,DateWorked, ProjectID, WorkDescription, BillableHours, BillingRate, WorkCodeID, Location
from @tempXMLTimeCardWorked


-- commit transaction, and exit
COMMIT TRANSACTION
set @Result = @NewTimeCardID
RETURN 0

-- Error Handler
ErrorHandler:
-- see if transaction is open
IF @@TRANCOUNT > 0
BEGIN
-- rollback tran
ROLLBACK TRANSACTION
END
-- set failure values
SET @Result = -1
RETURN -1

go

View 1 Replies View Related

Right Code Statements Of SqlConnection &&amp; ConnectionString For Connecting A Database In Database Explorer Of VB 2005 Express?

Feb 14, 2008

Hi all,

In the VB 2005 Express, I can get the SqlConnection and ConnectionString of a Database "shcDB" in the Object Explorer of SQL Server Management Studio Express (SSMSE) by the following set of code:
///--CallshcSpAdoNetVB2005.vb--////

Imports System.Data

Imports System.Data.SqlClient

Imports System.Data.SqlTypes

Public Class Form1

Public Sub InsertNewFriend()

Dim connectionString As String = "Data Source=.SQLEXPRESS;Initial Catalog=shcDB;Integrated Security=SSPI;"

Dim connection As SqlConnection = New SqlConnection(connectionString)

Try

connection.Open()

Dim command As SqlCommand = New SqlCommand("sp_insertNewRecord", connection)

command.CommandType = CommandType.StoredProcedure
.......................................
etc.
///////////////////////////////////////////////////////
If the Database "shcDB" and the Stored Procedure "sp_inertNewRecord" are in the Database Explorer of VB 2005 Express, I plan to use "Data Source=local" in the following code statements to get the SqlConnection and ConnectionString:
.........................
........................

Dim connectionString As String = "Data Source=local;Initial Catalog=shcDB;Integrated Security=SSPI;"

Dim connection As SqlConnection = New SqlConnection(connectionString)

Try

connection.Open()

Dim command As SqlCommand = New SqlCommand("sp_insertNewRecord", connection)

command.CommandType = CommandType.StoredProcedure
........................
etc.

Is the "Data Source=local" statement right for this case? If not, what is the right code statement for my case?

Please help and advise.

Thanks,
Scott Chang

View 6 Replies View Related

Common Table Expression

May 28, 2008

Hi
 
I was studying Common Table expression in Sql server 2005.
I have written the code
Declare @PictureArray as varchar(200)
Set @PictureArray = '';
with UserProfile_CTE(UserPicture)
As(
select @PictureArray = @PictureArray + '~' + PictureName from UserPicture where UserProfileID = 1102
select @PictureArray
)
select * from UserProfile_CTE
 
But I am getting the error
Incorrect syntax near '='
I am getting the error in the lineselect @PictureArray = @PictureArray + '~' + PictureName from UserPicture where UserProfileID = 1102
But I don't know the reason for this,
Kindly advice
Regards
Karan 
 

View 3 Replies View Related

Delete The Common Row Of A Table

Jan 7, 2006

hi i am using MS SQL Server 2000, i want to delete the common row from a table

table name EMP
rows
Eno Name Sal
1 Jim 1000
2 Mark 1200
1 Jim 1000
2 Mark 1250
1 Jim 1300

no primary key defile in to the table ....

i want to delete the row of
1 Jim 1000

please anybody can can help me ...

samarjit

View 1 Replies View Related

Common Table Expression?

Jul 20, 2005

What is the SQL Server equivalent of DB2 common table expressions? Forexample,with gry(year,count) as(select floor(sem/10),count(distinct ssn)from gradesgroup by floor(sem/10))select year,sum(count) Head_Count from grygroup by yearhaving year >= 1980;N. ShamsundarUniversity of Houston

View 2 Replies View Related

Common Need: History Table

Jan 22, 2008

Hi there!

I'm working on an application designed like this:
There's a table "DailyTransations" (DT) containing daily transactions...
Then there's an archive table "TransationsArchive" (TA) with the exact same structure.

When a record is inserted in DT, it is also in TA (via a trigger) and the reporting is done against TA.
Now for performance issues, we delete from DT the records older than 2 days since they are not needed for processing.

First, what do you think of that implementation?

We thought about using partitions based on the transaction date and completely eliminate TA, but it seems once a record is assigned to a partition, it is not moved automatically...

What is the common solution for this need?

Thanks
Frantz

View 4 Replies View Related

Most Common Connection Method To SQL 2005

Aug 8, 2007

I am currently using ADO from an application to connect to SQL 2005. Is thisthe preferred way, or is that the most common method? I was told I need touse an API. Which API? Thanks.Charlie

View 1 Replies View Related

Index On Used Table Common Fields

Jan 6, 2012

I would like to know if SQL Server creates automatic index on the used tables' common fields.

For example:

Code:
CREATE VIEW [dbo].[ORMAN]
AS
SELECT dbo.PARSEL.OBJECTID, dbo.PARSEL.ADAPARSEL, dbo.PARSEL.ORMANADI, dbo.PARSEL.MULKIYET, dbo.PARSEL.ALAN, dbo.PARSEL.YERKOD,
dbo.PARSEL.UYG_KAN, dbo.PARSEL.KomNo, dbo.PARSEL.KadKan, dbo.PARSEL.Mescere, dbo.PARSEL.ACIKLAMA, dbo.PARSEL.URETIM_YONTEMI,

[Code] .....

On the above view example, if table PARSEL has 1 million records do I have to create an index for PARSELDURUM or when I create a view does SQL server create automatic virtual index?

View 6 Replies View Related

When Connect Two Table Should They Always Have Column In Common With Each Other?

Jun 27, 2014

When I connect two table should they always have a column in common with each other?For example the 'patients' and 'doctors' tables in that ER are connected to say each doctor can have many patients and each patient can have many doctors, but they have no columns in common. Is it right?

View 8 Replies View Related

Can't Execute Sql In Code-behind

Apr 18, 2008

 I found a example of using a button inside of a gridview at http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield.aspx.I modified the code-behind and added:      // Insert the producer into the database      SqlDataSource sds = selectedRow.FindControl("sqlItemInsertIntoListing") as SqlDataSource;      sds.Insert(); but the page throws an error.Can someone look at my code-behind and show me how to execute the line 56 in the code-behind?  Thanks.   Object reference not set to an instance of an object.



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.NullReferenceException: Object reference not set to an instance of an object.

Source Error:




Line 55: // Insert the producer into the databaseLine 56: SqlDataSource sds = selectedRow.FindControl("sqlItemInsertIntoListing") as SqlDataSource;Line 57: sds.Insert();Line 58:Line 59: } Below is my code: ASPX PAGE:    <asp:Label ID="Message" ForeColor="Red" runat="server" AssociatedControlID="CustomersGridView" />    <!-- Populate the Columns collection declaratively. -->    <asp:GridView ID="CustomersGridView" DataSourceID="CustomersSqlDataSource" DataKeyNames="ItemID"        AutoGenerateColumns="False" OnRowCommand="CustomersGridView_RowCommand"         runat="server" AllowPaging="True" AllowSorting="True" PageSize="50">        <Columns>            <asp:BoundField DataField="ProducerName" HeaderText="Producer" SortExpression="ProducerName" />            <asp:BoundField DataField="ItemName" HeaderText="Item" SortExpression="ItemName" />            <asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />            <asp:BoundField DataField="RegionMasterName" HeaderText="Region" SortExpression="RegionMasterName" />            <asp:BoundField DataField="CountryName" HeaderText="Country" SortExpression="CountryName" />            <asp:BoundField DataField="StateName" HeaderText="State" SortExpression="StateName" />            <asp:TemplateField HeaderText="ItemID" InsertVisible="False" Visible="false" SortExpression="ItemID">                <ItemTemplate>                    <asp:Label ID="ItemID" runat="server" Text='<%# Bind("ItemID") %>' Visible="false"></asp:Label>                    <asp:SqlDataSource ID="sqlItemInsertIntoPart" runat="server" ConnectionString="<%$ ConnectionStrings:VBJimboConn %>"                        InsertCommand="INSERT INTO [ZCPart] ([PartUserId], [PartItemID]) VALUES (@PartUserId, @PartItemID)" OnInserting="sqlItemInsertIntoPart_Inserting" >                        <InsertParameters>                            <asp:Parameter Name="PartUserId" />                            <asp:ControlParameter Name="PartItemID" ControlID="ItemID" PropertyName="Text" Type="Int32" />                        </InsertParameters>                    </asp:SqlDataSource>                </ItemTemplate>            </asp:TemplateField>            <asp:ButtonField ButtonType="Button" CommandName="Select"                Text="Add to Part" Visible="True" />            <asp:HyperLinkField DataNavigateUrlFields="ItemID"                 DataNavigateUrlFormatString="ItemDetails.aspx?ItemID={0}" Text="Details" />        </Columns>    </asp:GridView>        <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:CONNSTG %>"....>        </asp:SqlDataSource>  CODE-BEHIND:using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;partial class Inventory_InventoryList : System.Web.UI.Page{    protected void Page_Load(object sender, System.EventArgs e)    {        if (!Page.IsPostBack)        {            if (!User.Identity.IsAuthenticated)            {                CustomersGridView.Columns[CustomersGridView.Columns.Count - 2].Visible = false;            }        }    }    protected void sqlItemInsertIntoPart_Inserting(object sender, System.Web.UI.WebControls.SqlDataSourceCommandEventArgs e)    {        e.Command.Parameters["@PartUserId"].Value = Membership.GetUser().ProviderUserKey;    }// Source for gvInventoryList to display message: http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield.aspx  protected void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)  {    // If multiple ButtonField column fields are used, use the    // CommandName property to determine which button was clicked.    if(e.CommandName=="Select")    {      // Convert the row index stored in the CommandArgument      // property to an Integer.      int index = Convert.ToInt32(e.CommandArgument);          // Get the last name of the selected author from the appropriate      // cell in the GridView control.      GridViewRow selectedRow = CustomersGridView.Rows[index];      TableCell contactName = selectedRow.Cells[1];      string contact = contactName.Text;        // Display the selected author.      Message.Text = "You selected " + contact + ".";            // Insert the producer into the database      SqlDataSource sds = selectedRow.FindControl("sqlItemInsertIntoListing") as SqlDataSource;      sds.Insert();    }  }}

View 2 Replies View Related

Execute .sql From Code?

Mar 31, 2005

How can I execute am .sql script that was generated from SQL Server?

View 4 Replies View Related







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