Showing posts with label below. Show all posts
Showing posts with label below. Show all posts

Thursday, March 29, 2012

Granting UPDATE for only certain columns in a table

I have tried using the SQL statement shown below to grant UPDATE permissions for a single column in a single table to a user with db_datareader privileges.

grant update (col_1) on trs.dbo.table_1 to calc

When I then run a SQL script that has an UPDATE for col_1 on trs.dbo.table_1, I get an error message

Msg 230, Level 14, State 1, Line 2100

UPDATE permission denied on column 'col_2' of object 'table_1', database 'TRS', schema 'dbo'.

Why is the error message referring to "col_2" when my SQL statement is trying to update "col_1"?

When I performed the "grant" I did it with an account that has db_owner, db_securityadmin, and db_ddladmin privileges.

This worked in SQL Server 2000. What must I do to get it to work in SQL Server 2005?

Sorry Dan - can you show us the update query?|||

You are going to have to dig deeper. The only scenario that I can think of where an update to another column causes an update to another column causing issues like this is with a trigger with dynamic SQL (a real no-no in almost all cases, but it could exist). The fact that you have appended database names to the ddl makes me curious as to how that *might* cause issue, but I don't even see how anything cross-database could be an issue either.

Here is a script that shows what I am meaning:

create table test
(
column1 int,
column2 int
)
go
create user fred without login
go
execute as user = 'fred'
go
update test
set column1 = 1
/*
Msg 229, Level 14, State 5, Line 1
The UPDATE permission was denied on the object 'test', database 'tempdb', schema 'dbo'.
*/
go
revert
go
grant update (column1) on test to fred
go
execute as user = 'fred'
go
update test
set column1 = 1
/*
(0 row(s) affected)
*/
update test
set column2 = 1
/*
Msg 230, Level 14, State 1, Line 1
The UPDATE permission was denied on the column 'column2' of the object 'test', database 'tempdb', schema 'dbo'.
*/
go
revert
go
create trigger test$updateColumn1
on test
after update
as
begin
exec('
update test
set column2 = 2')
end
go
execute as user = 'fred'
go
update test
set column1 = 1
/*
Msg 230, Level 14, State 1, Line 2
The UPDATE permission was denied on the column 'column2' of the object 'test', database 'tempdb', schema 'dbo'.
*/

If you could post a full example like this showing your issue I think that you might find your error, or certainly one of us can help you out.

|||

Thanks for your support.

Here is a small bit of code that is able to produce the problem. It seems to be associated with having a JOIN in the UPDATE statement. An UPDATE without the JOIN works just fine.

Using a DB_OWNER account perform the following table creation, insert, and grant commands:

create table trs.dbo.people
(
name varchar(10),
sex varchar(10),
age smallint
)

insert into people values ('tom', 'male', 10)
insert into people values ('jane', 'female', 18)
insert into people values ('sue', 'female', 22)

create table trs.dbo.grads
(
name varchar(10),
grad_yr varchar(4)
)

insert into grads values ('jane', '2006')
insert into grads values ('sue', '2002')

grant update (age) on trs.dbo.people to calc

Then, from the db_datareader account, calc, run the following UPDATE statements, one at a time.

update p
set age = 40
from trs.dbo.people p
where (age is not null)
;

update p
set age = 35
from trs.dbo.people p
inner join trs.dbo.grads g
on p.name = g.name
where (age is not null)
;

The first one works. The second one fails with error message

Msg 230, Level 14, State 1, Line 1

UPDATE permission denied on column 'name' of object 'people', database 'TRS', schema 'dbo'.

Does this help?

|||Very nice. I have no answer as to why this is, but I will check around and let you know.|||Thanks!|||Do you have select permission on the other columns?

I know it's complaining that you don't have UPDATE permission... but it's complaining about your access to another column that's involved in the join.

Rob|||

Rob,

If I enter SELECT statements against the two tables, while connected as "CALC", all the rows from each table are returned.

select * from grads;

select * from people;

I have also tried using the DB_OWNER connection to explicity GRANT SELECT access to those tables, and still get the same error message when I try to update the AGE column, as in the example above, while connected as "CALC".

grant select on trs.dbo.people to calc
grant select (name) on trs.dbo.people to calc
grant select on trs.dbo.grads to calc

Dan

|||Ok, so that idea wasn't right. ;)

It's somehow related to the fact that you're joining the table you're updating to another table, and the engine thinks that it needs to be able to update that column too. It doesn't of course, but the fact that the column is used in the query must be confusing it somehow.

I assume this works just fine if you grant update access to the name column too?

One workaround might be to wrap it up in a table expression, but if that works, it'll just be down to luck.

Rob|||

The same code runs just fine with SQL Server 2000. I only ran into a problem when I tried moving it over to SQL Server 2005.

If I grant UPDATE access on the NAME column, as identified in the Error message, then the code runs.

But I hate to do that, since CALC is supposed to be a relatively "unprivileged" user, with db_datareader general privileges only, and CREATE TABLE privileges -- and in my actual application, these other columns are the PRIMARY KEY columns in the tables.

Adding a new column to the table, a column to which CALC has UPDATE permission, was a way of avoiding creating an entirely new table for CALC to own, with 500,000 rows, and a 20-byte primary key that incorporates 5 columns. Had I created such a new table my processing queries would have to JOIN this table to the 500,000 row counterpart. Instead of such a JOIN I added a new column as a simpler, faster solution.

Dan

|||Hmm... I'll have to do some more hunting. I'd like to say "try using a cte or view", or something like that (based on the fact that you might be able to update a view without it thinking it needs to be able to update the joining column), but I actually don't know if that will help. I'll have to recreate the situation locally and try some things.

But hopefully some of the other guys will already know the answer to this.

Rob|||

This seems like such a "natural" thing to have to do, in most any application that requires user permissions to only certain columns in a table.

Consider a table that connects salary to social security number. If you want to allow someone to edit SALARY, must you also allow them to edit SOCIAL SECURITY NUMBER?

What if you are running a medical office and have some sort of PATIENT NUMBER in the medical records. If you want to edit information on their account, such as their ZIP CODE, must you also allow them to edit the PATIENT NUMBER?

Is there maybe a greater need in SQL Server 2005 to create a new ROLE for every different set of permissions that one might need in the database, rather than use GRANT UPDATE to customize access to different users?

I'm not now at my office where I could try it, but I'm wondering if some SYSTEM table stores UPDATE permissions, and if a user has NOT received GRANT or DENY UPDATE permissions on a column in a table, maybe an INNER JOIN is being used, rather than an OUTER JOIN on the permissions table. If that is true, I suppose I can DENY UPDATE on the NAME column in the example, and the query should work, because it finds an entry in the permissions table for the NAME column, even though that entry is "DENY." So tomorrow at the office I'll try DENY UPDATE (name) on TRS.DBO.PEOPLE to CALC. (I'll have to check the syntax on the DENY statement. I think I noticed one in the past few days.)

Dan

|||

This is almost clearly a bug that I posted here: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=257897

A (not terribly satisfying) workaround is to move the join to a subquery:

update p set age = 35
from trs.dbo.people p
where p.name in (select p2.name
from trs.dbo.people p2
inner join trs.dbo.grads g
on p.name = g.name
where (age is not null))

Here is the simple repro with users I posted:

create database trs
go
use trs
go
create table trs.dbo.people
(
name varchar(10),
sex varchar(10),
age smallint
)

insert into people values ('tom', 'male', 10)
insert into people values ('jane', 'female', 18)
insert into people values ('sue', 'female', 22)

create table trs.dbo.grads
(
name varchar(10),
grad_yr varchar(4)
)

insert into grads values ('jane', '2006')
insert into grads values ('sue', '2002')
go
create user calc without login
sp_addrolemember 'db_datareader','calc'
go
grant update (age) on trs.dbo.people to calc
go

--Then, from the db_datareader account, calc, run the following UPDATE
statements, one at a time.
execute as user = 'calc'
go

update p
set age = 40
from trs.dbo.people p
where (age is not null)
;

update p
set age = 35
from trs.dbo.people p
inner join trs.dbo.grads g
on p.name = g.name
where (age is not null)
;

/*
Msg 230, Level 14, State 1, Line 1
The UPDATE permission was denied on the column 'name' of the object
'people', database 'trs', schema 'dbo'.
*/
--

|||

Louis,

Thanks for posting that to the MS "feedback" site.

I tried my "DENY UPDATE" idea, but it didn't fix anything: the same error message was obtained for the same UPDATE statement.

There aren't many places in my code where I am performing updates on columns where the GRANT UPDATE permission is limited to certain columns -- maybe a few dozen. I'll just make the code edits corresponding to your suggestion, and maybe un-do them if/when a patch occurs.

Thanks again.

Dan

|||

Louis,

I reworked my code for SQL Server 2005, using the technique you suggested (or something quite similar):

update p set age = 35
from trs.dbo.people p
where p.name in (select p2.name
from trs.dbo.people p2
inner join trs.dbo.grads g
on p.name = g.name
where (age is not null))

In all but a single instance, this solution worked just fine.

In the remaining instance, the value that I need for the SET clause is from the JOINed table. Were we using the example I supplied (rather than my actual code), this could appear as

update p
set age = cast(g.grad_yr as int) + 18 - 2006
from trs.dbo.people p
inner join trs.dbo.grads g
on p.name = g.name
where (age is not null)

I didn't see any easy way around this, other than to create a CURSOR on "select distinct GRAD_YR from GRADS" and using a LOOP over the CURSOR values, and having code like

update p
set age = @.grad_yr + 18 - 2006
from trs.dbo.people p
where (age is not null) and p.name in (select distinct name from trs.dbo.grads where grad_yr = @.grad_yr)

I am thankful that the number of values for my CURSOR is less than 10, in my actual application.

If you can think of a better alternative, I would be happy to learn of it.

Thanks.

Dan

Friday, March 23, 2012

GRANT EXEC Problem

Hi,
SQL Server does not like my stored procedure below. It complains
about the GRANT EXEC line
What am I doing wrong?
JD
----
DECLARE @.PROCNAME varchar(50)
DECLARE cPROCNAME CURSOR FOR
SELECT NAME
FROM SYSOBJECTS
WHERE XTYPE = 'P' AND CATEGORY = 0
ORDER BY NAME
OPEN cPROCNAME
FETCH NEXT FROM cPROCNAME INTO @.PROCNAME /* Prime the cursor */
WHILE @.@.FETCH_STATUS = 0
BEGIN
GRANT EXEC ON @.PROCNAME TO PUBLIC <--Problem here
FETCH NEXT FROM cPROCNAME INTO @.PROCNAME
END
CLOSE cPROCNAME
DEALLOCATE cPROCNAMEYou cannot do a grant on a variable. You'll have to use dynamic SQL. (BTW,
in SQL 2005, you can do a GRANT EXEC on an entire SCHEMA)
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Joe Delphi" <delphi561@.nospam.cox.net> wrote in message
news:JZLff.5127$xu.344@.fed1read01...
Hi,
SQL Server does not like my stored procedure below. It complains
about the GRANT EXEC line
What am I doing wrong?
JD
----
DECLARE @.PROCNAME varchar(50)
DECLARE cPROCNAME CURSOR FOR
SELECT NAME
FROM SYSOBJECTS
WHERE XTYPE = 'P' AND CATEGORY = 0
ORDER BY NAME
OPEN cPROCNAME
FETCH NEXT FROM cPROCNAME INTO @.PROCNAME /* Prime the cursor */
WHILE @.@.FETCH_STATUS = 0
BEGIN
GRANT EXEC ON @.PROCNAME TO PUBLIC <--Problem here
FETCH NEXT FROM cPROCNAME INTO @.PROCNAME
END
CLOSE cPROCNAME
DEALLOCATE cPROCNAME

Wednesday, March 21, 2012

Grand Total in Matrixes

Hi,
I am working on matrix report that uses 3 matrixes like below.
In Grand Total matrix, I want to sum matrix 1 and matrix2 subtotals and
display as Grand Total. I had a difficulty to find out the expression for
this(how to reference the subtotals in matrixes?)?
Can we do this or any limitations?
Matrix 1:
Week1 Week2
Sub Total 10 20
Matrix 2:
Week1 Week2
Sub Total 15 25
Grand Total
Week1 Week2
Grand Total 25 45
Any pointers in this regard is appreciated
Thanks
BhaskarOn Nov 16, 5:08 pm, Bhaskar <Bhas...@.discussions.microsoft.com> wrote:
> Hi,
> I am working on matrix report that uses 3 matrixes like below.
> In Grand Total matrix, I want to sum matrix 1 and matrix2 subtotals and
> display as Grand Total. I had a difficulty to find out the expression for
> this(how to reference the subtotals in matrixes?)?
> Can we do this or any limitations?
> Matrix 1:
> Week1 Week2
> Sub Total 10 20
> Matrix 2:
> Week1 Week2
> Sub Total 15 25
> Grand Total
> Week1 Week2
> Grand Total 25 45
> Any pointers in this regard is appreciated
> Thanks
> Bhaskar
Since you have multiple columns that have subtotals, you most likely
will want to sum the subtotals together as part of another report
dataset (via a separate stored procedure/query). If there was only one
subtotal column per matrix, you might have been able to reference
aggregates via an expression similar to this.
=Sum(Fields!Week1.Value, "dsMatrix1") + Sum(Fields!Week1.Value,
"dsMatrix2")
Where dsMatrix1 and dsMatrix2 are the example dataset names used for
Matrix1 and Matrix2 respectively.
Hope this helps.
Regards,
Enrique Martinez
Sr. Software Consultant|||Thanks Enrique. yeah.. i tried to avoid another query or sp to get the grand
total.
looks like there is no other way. :)
Bhaskar
"EMartinez" wrote:
> On Nov 16, 5:08 pm, Bhaskar <Bhas...@.discussions.microsoft.com> wrote:
> > Hi,
> >
> > I am working on matrix report that uses 3 matrixes like below.
> >
> > In Grand Total matrix, I want to sum matrix 1 and matrix2 subtotals and
> > display as Grand Total. I had a difficulty to find out the expression for
> > this(how to reference the subtotals in matrixes?)?
> > Can we do this or any limitations?
> >
> > Matrix 1:
> >
> > Week1 Week2
> > Sub Total 10 20
> >
> > Matrix 2:
> > Week1 Week2
> > Sub Total 15 25
> >
> > Grand Total
> >
> > Week1 Week2
> > Grand Total 25 45
> >
> > Any pointers in this regard is appreciated
> >
> > Thanks
> > Bhaskar
>
> Since you have multiple columns that have subtotals, you most likely
> will want to sum the subtotals together as part of another report
> dataset (via a separate stored procedure/query). If there was only one
> subtotal column per matrix, you might have been able to reference
> aggregates via an expression similar to this.
> =Sum(Fields!Week1.Value, "dsMatrix1") + Sum(Fields!Week1.Value,
> "dsMatrix2")
> Where dsMatrix1 and dsMatrix2 are the example dataset names used for
> Matrix1 and Matrix2 respectively.
> Hope this helps.
> Regards,
> Enrique Martinez
> Sr. Software Consultant
>

Grabbing DATENAME from date only returns January

why is the below only giving me January?

CAST(DATENAME(Month, datepart(month, ph.systemmonth)) AS varchar(15))

What did you expect ?

-Jens Suessmeyer.

http://www.sqlserver2005.de|||

I solved it:

Results:

0000002 MA 0000002 25 5.00 January 1 2005
0000002 MA 0000002 25 20.00 January 1 2005
0000002 MA 0000002 25 43.00 January 1 2005
0000002 MA 0000002 25 1264.20 January 6 2005
0000002 MA 0000002 25 1344.47 January 6 2005
0000002 MA 0000002 25 210.23 January 10 2005
0000002 MA 0000002 25 211.25 January 10 2005

Expected Results:

0000002 MA 0000002 25 5.00 January 1 2005
0000002 MA 0000002 25 20.00 January 1 2005
0000002 MA 0000002 25 43.00 January 1 2005
0000002 MA 0000002 25 1264.20 June 6 2005
0000002 MA 0000002 25 1344.47 June 6 2005
0000002 MA 0000002 25 210.23 October 10 2005
0000002 MA 0000002 25 211.25 October 10 2005

Resolution:

CAST(DATENAME(Month, '2006/' + Convert(varchar(2), ph.systemmonth)) + '/1') AS varchar(15)) as SystemMonth

for a real date field (which systemmonth was not in this case...since it only contained the month) you can do this:

CAST(DATENAME(Month, '2006/' + Convert(varchar(2), datepart(mm,getdate())) + '/1') AS varchar(15)) as SystemMonth,

Monday, March 19, 2012

Got Microsoft OLE DB Provider for ODBC Drivers error '80004005' when running Stored Procedures

when i am running a Stored Procedures, system always returns me error message below and Stored Procedures stops. please help

Microsoft OLE DB Provider for ODBC Drivers error

'80004005'

[Microsoft][ODBC SQL Server Driver] Received an unrecognized datatype 0 from

TDS data stream

sometime it returns error messge like, TDS Buffer Length Too Large
or
Unknown token received from SQL Server

or
Protocol error in TDS stream
or
Bad token from SQL Server: Datastream processing out of sync.
or
Invalid cursor state
or
TDS Buffer Link Too Large
or
Function sequence error

Many thanks, Please help, appreciated

Can you post more information about the configuration:

- What version of SQL Server do you use?

- What OLEDB provider do you use (e.g., SQLOLEDB, SQL Native Client?)?

- What is the definition of relevan tables?

- Code for the stored procedure and for the application calling it (omit any confidential information)?

|||

Thanks Peter:

it's SQL Server 2000 sp4, this problem happens on the OLEDB provider ODBC driver. the detials of sproc is that there is one sproc calling other 4 different sprocs to update 4 different table (about 30,000 columns need to be updated in each table). and it will run only once a month automaticly by Job.

I also tried to run those 4 sprocs separately and manually, still get the same problem, somehow.

cheers

|||anyone can help?|||

Could be a network performance or configuration error.

http://support.microsoft.com/default.aspx/kb/176256

Got Microsoft OLE DB Provider for ODBC Drivers error '80004005' when running Stored Procedures

when i am running a Stored Procedures, system always returns me error message below and Stored Procedures stops. please help

Microsoft OLE DB Provider for ODBC Drivers error

'80004005'

[Microsoft][ODBC SQL Server Driver] Received an unrecognized datatype 0 from

TDS data stream

sometime it returns error messge like, TDS Buffer Length Too Large
or
Unknown token received from SQL Server

or
Protocol error in TDS stream
or
Bad token from SQL Server: Datastream processing out of sync.
or
Invalid cursor state
or
TDS Buffer Link Too Large
or
Function sequence error

Many thanks, Please help, appreciated

Can you post more information about the configuration:

- What version of SQL Server do you use?

- What OLEDB provider do you use (e.g., SQLOLEDB, SQL Native Client?)?

- What is the definition of relevan tables?

- Code for the stored procedure and for the application calling it (omit any confidential information)?

|||

Thanks Peter:

it's SQL Server 2000 sp4, this problem happens on the OLEDB provider ODBC driver. the detials of sproc is that there is one sproc calling other 4 different sprocs to update 4 different table (about 30,000 columns need to be updated in each table). and it will run only once a month automaticly by Job.

I also tried to run those 4 sprocs separately and manually, still get the same problem, somehow.

cheers

|||anyone can help?|||

Could be a network performance or configuration error.

http://support.microsoft.com/default.aspx/kb/176256

Wednesday, March 7, 2012

going from sqlconnection and sqlreader to using a tableadapter and ????

Below is my code right now Im using a direct sqlconnection for each request.? I would like to use Tableadapters and/or my BLL code like the rest of my sites pages.? I cant find how to do this progamatically and using the xmltextwriter. (Also i need to be able to name the xml output nodes like below)

Thanks for the help.

Neil




Private Sub GetAllEvents(ByVal SqlString)

? ? ? ? Response.Clear()

? ? ? ? Response.ContentType = "text/xml"

? ? ? ? Dim objX As New XmlTextWriter(Response.OutputStream, Encoding.UTF8)

? ? ? ? objX.WriteStartDocument()

? ? ? ? objX.WriteStartElement("Events")

? ? ? ? Dim objConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\*********.mdf;Integrated Security=True;User Instance=True")

? ? ? ? objConnection.Open()

? ? ? ? Dim sql As String = SqlString

? ? ? ? Dim objCommand As New SqlCommand(sql, objConnection)

? ? ? ? Dim objReader As SqlDataReader = objCommand.ExecuteReader()

? ? ? ? While objReader.Read()

? ? ? ? ? ? objX.WriteStartElement("Event")

? ? ? ? ? ? objX.WriteAttributeString("EventId", objReader.GetInt32(0))

? ? ? ? ? ? objX.WriteAttributeString("EventName", objReader.GetString(1))

? ? ? ? ? ? objX.WriteAttributeString("EventDescription", objReader.GetString(2))

? ? ? ? ? ? objX.WriteAttributeString("EventDate", objReader.GetDateTime(3))

? ? ? ? ? ? objX.WriteAttributeString("CurrentDate", Date.Now.ToString)

? ? ? ? ? ? If Not objReader.IsDBNull(12) Then

? ? ? ? ? ? ? ? objX.WriteAttributeString("EventImage", objReader.GetString(12))

? ? ? ? ? ? End If

? ? ? ? ? ? objX.WriteEndElement()

? ? ? ? End While

? ? ? ? objReader.Close()

? ? ? ? objConnection.Close()

? ? ? ? objX.WriteEndElement()

? ? ? ? objX.WriteEndDocument()

? ? ? ? objX.Flush()

? ? ? ? objX.Close()

? ? ? ? Response.End()


? ? End Sub

Hi,

If you wish to write all the content of the query result to an Xml, I suggest you do the following step:

1. Use a SqlDataAdapter to fill a DataSet.
2. Call DataSet.WriteXml(REsponse.OutputStream) to output it.

Dim objConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\*********.mdf;Integrated Security=True;User Instance=True")
objConnection.Open()
Dim sql As String = SqlString
Dim DA As New SqlDataAdapter(sql, objConnection)
Dim ds As New DataSet()
DA.Fill(ds)
ds.WriteXml(Response.OutputStream)

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!

|||

That works great, However I need to have complete control over which fields are put in nodes and into attributes. We are passing the xml into flash and need to have control over each field. I have pre made table adapters and a BLL that handles all of the "BackEnd" Functions for administration. Trying to use those for the xml output as well(Dont want to dble code). Thanks for the help

Friday, February 24, 2012

Global temp table permissions

I have a pivot table implementation, part of which is posted below. It
returns no errors in query analyzer, but when profiler is run, it shows
that "Error 208" is happening. I looked that up in BOL and it means
that an object doesn't exist. This block of code below works fine on my
local development machine, but not on our shared development server
until I go into the tempdb and make the user have the role db_owner.
Even wierder is that when I do a select * from ##pivot there is no
error, but if I specify the single column name (pivot) i.e. select
pivot from ##pivot, it takes the error...

Obviously this is a rights issue, but is there any way around this
other than making the user owner of tempdb??

declare @.select varchar(8000), @.PackageId int
set @.PackageId = 10
set @.select = '
select
Company = COALESCE(Users.Company, Contact.Company, ''''),
SubContractPackageVendor.Id, SubContractPackageVendor.isActive,
SubContractPackageVendor.isAwarded,
SubContractPackageVendor.UserOrContactType,
SubContractPackageVendor.UserOrContactId
FROM
SubContractPackageVendor
LEFT JOIN SubContractPackage ON SubContractPackageVendor.PackageId =
SubContractPackage.Id

LEFT JOIN Users ON UserOrContactType = ''User'' AND UserOrContactId =
Users.UserId
LEFT JOIN UserRoles ON UserOrContactType = ''User'' AND
UserRoles.UserId = Users.UserId AND UserRoles.ProjectId =
SubContractPackage.ProjectId
LEFT JOIN Role ON Role.RoleId = UserRoles.RoleId

LEFT JOIN Contact ON UserOrContactType = ''Contact'' AND
UserOrContactId = Contact.Id

LEFT JOIN SubContractLineItem ON
SubContractLineItem.RefType = ''Package'' AND
SubContractLineItem.RefId = SubContractPackageVendor.PackageId
LEFT JOIN SubContractLineItem as SubContractPackageVendorItem ON
SubContractPackageVendorItem.RefType = ''PackageVendor'' AND
SubContractPackageVendorItem.RefId = SubContractPackageVendor.Id AND
SubContractPackageVendorItem.RefSubId = SubContractLineItem.Id
Where
SubContractPackageVendor.PackageId = ' + CAST(@.PackageId as varchar)
+ '
GROUP BY
SubContractPackageVendor.Id, SubContractPackageVendor.isActive,
SubContractPackageVendor.isAwarded, Users.Company, Contact.Company,
SubContractPackageVendor.UserOrContactType,
SubContractPackageVendor.UserOrContactId'
--print @.sql

declare @.sumfunc varchar(100),
@.pivot varchar(100),
@.table varchar(100),
@.FieldPrefix varchar(5),
@.TotalFieldName varchar(50),
@.PivotFieldFilter varchar(1000)

select
@.sumfunc ='Sum(isnull(SubContractPackageVendorItem.Total,0) )' ,
@.pivot ='SubContractLineItem.Category' ,
@.table ='SubContractLineItem' ,
@.FieldPrefix='~' ,
@.TotalFieldName = 'Total' ,
@.PivotFieldFilter = ' AND RefType=''Package'' AND RefId=' +
CAST(@.PackageId as varchar)

set nocount on

DECLARE @.sql varchar(8000), @.delim varchar(1), @.TotalSql varchar(8000)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

EXEC ('SELECT ' + @.pivot + ' AS pivot INTO ##pivot FROM ' + @.table + '
WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @.pivot + ' FROM ' +
@.table + ' WHERE '
+ @.pivot + ' Is Not Null ' + @.PivotFieldFilter)

SELECT @.sql='', @.sumfunc=stuff(@.sumfunc, len(@.sumfunc), 1, ' END)' )

SELECT @.delim=CASE Sign( CharIndex('char',
data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'

select * from ##pivot

DROP TABLE ##pivotpb648174 (google@.webpaul.net) writes:
> I have a pivot table implementation, part of which is posted below. It
> returns no errors in query analyzer, but when profiler is run, it shows
> that "Error 208" is happening.

Because of deferred name resolution, you see quite a lot of 208 in
Profiler which are "false alarms". When SQL Server first compiles your
batch, ##pivot does not exist which causes a 208 error which is then
suppressed. When you hit a statement where ##pivot is referred, the
batch is recompiled.

> I looked that up in BOL and it means that an object doesn't exist. This
> block of code below works fine on my local development machine, but not
> on our shared development server until I go into the tempdb and make the
> user have the role db_owner. Even wierder is that when I do a select *
> from ##pivot there is no error, but if I specify the single column name
> (pivot) i.e. select pivot from ##pivot, it takes the error...

And that is a 208 and not a 207 ("Column does not exist"?) There could
be an old ##pivot which hanging around.

In any case, I'm not a friend of global temp tables, and I don't recommend
use of them. I don't know what your underlying problem is, but my favourite
is a spid-keyed table. That is, a permanent table, but which is intended
to hold any data only transitionary. The first column is spid, and in
the simplest form you use @.@.spid for the value.

Now, @.@.spid, does not work well, if you are to share the table between
processes. For this reason, we use negative values in these cases. You
could simply do:

BEGIN TRANSACTION
SELECT @.nextksy = coalesce(MIN(spid), 0) - 1 FROM tbl (UPDLOCK)

INSERT tbl (spid, ...) VALUES (@.nextkey, ...)

COMMIT TRANSACTION

Of course you should take measures to have old data removed from the
table once you are done with it. But that is really not any different
from the global temp table. Except, that is, you have more control
over it.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Why does giving the user running the process db_owner access solve the
problem? Is there some other way other than rewriting large blocks of
working code?|||pb648174 (google@.webpaul.net) writes:
> Why does giving the user running the process db_owner access solve the
> problem? Is there some other way other than rewriting large blocks of
> working code?

Judging from your post, the code is not working in the general case, only
in a protected environment.

I don't know where db_owner comes into play. I played around a little
with a plain user and global temp tables, but I did not ran into any
problems.

Then again you have not specified what "not works on the shared development
server" means. Do you get error messages? Incorrect results?

Maybe the problem is access rights to the other tables, and not with
the global temp table?

Anyway, global temp tables, is in my opinion a poor solution, because
there is always a lot uigly what-if scenarios. Whence my recommentation
to change to something better.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Actually I specifically said "It returns no errors in query analyzer,
but when profiler is run, it shows that "Error 208" is happening" - it
is only on one machine that it does this, and the fix for that machine
was to give the user running the command db_owner access to the tempdb
database.

The reason I am using the global temp table implementation for this is
because the below statement correctly (and dynamically) creates the
type of the column automagically. If there is a way to do that with the
method you suggested, or better yet, to find out why giving the tempdb
db_owner access fixes the 208 error and keep the existing working,
tested and released code, that would be great. Lastly, if there is a
better way to perform a pivot table in SQL Server(with working sample),
I am all ears - this was simply the best I found that actually works.

EXEC ('SELECT ' + @.pivot + ' AS pivot INTO ##pivot FROM ' + @.table + '
WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @.pivot + ' FROM
' +
@.table + ' WHERE '
+ @.pivot + ' Is Not Null ' + @.PivotFieldFilter)|||pb648174 (google@.webpaul.net) writes:
> Actually I specifically said "It returns no errors in query analyzer,
> but when profiler is run, it shows that "Error 208" is happening" - it

And as I explained to you, the 208 in Profiler is a false alarm.

So you don't get any error, but how then you do conclude that it doesn't
work? Or don't you really have any problem at all? Do you get incorrect
results, or what is your real problem?

> is only on one machine that it does this, and the fix for that machine
> was to give the user running the command db_owner access to the tempdb
> database.

Or because when you reran the batch, the plan was in the cache, and the
208 did not happen behind the scenes.

db_owner could possibly have something to do with your reading
of INFORMATION_SCHEMA.COLUMNS, since that view is supposed to only
show things you have access to, so somesuch. Try using syscolumns
instead. (But here I am guessing very wildly of what you problem you
really have.)

> The reason I am using the global temp table implementation for this is
> because the below statement correctly (and dynamically) creates the
> type of the column automagically. If there is a way to do that with the
> method you suggested, or better yet, to find out why giving the tempdb
> db_owner access fixes the 208 error and keep the existing working,

Again, the 208 you see in Profiler is not a problem!

Rather than using SELECT INTO, create the table with CREATE TABLE. Then
you can use a plain #temp table.

> tested and released code, that would be great. Lastly, if there is a
> better way to perform a pivot table in SQL Server(with working sample),
> I am all ears - this was simply the best I found that actually works.

Popular for crosstabs and that sort of thing is RAC,
see http://www.rac4sql.net.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Ok, that worked great, thanks.

I was thinking I couldn't used the #temp table since it was doing an
exec sql select and had already tried the @.temp table style... I also
wish I would have seen that reference to tempdb in there, that was a
good educated guess. I pulled that pivot code from another site,
apparently it had some problems. It is now working well with a normal
#temp table (although I have to do some shenanigans to get the type of
the column correct, which that statement with the global temp table did
so easily.)

Thanks for the help!