Showing posts with label column. Show all posts
Showing posts with label column. Show all posts

Friday, March 30, 2012

Problem with CASE Expression

Hi, all here,

I have a problem with CASE expression in my SQL staments.

the problem is:

when I tried to just partly update the column a , I used the CASE expression : set a=case when b=null then 'null' end

the result was strange: then all the values for column a turned to null.

so what is the problem tho?

Thanks a lot in advance for any guidance.

Is it something like this you're trying to do?

create table #x ( a int null, b int null )
go
insert #x
select 1, 1 union all
select 2, null union all
select 3, 1 union all
select 4, null
go
select * from #x
go

a b
-- --
1 1
2 NULL
3 1
4 NULL

(4 row(s) affected)

update #x
set a = case when b is null then null else a end
go

select * from #x
go

a b
-- --
1 1
NULL NULL
3 1
NULL NULL

(4 row(s) affected)

drop table #x
go

/Kenneth

|||set a=case when b IS null then 'null' end|||The issue is with your comparison of the column value against NULL using equality operator. By default, <any non null value> <> NULL unless you set ANSI_NULLS to off and this affects few operations in the server. You can check the Books Online for more details. The recommended syntax is to use the IS NULL or IS NOT NULL clauses for checking NULL values.

Problem with BULK INSERT ASCII file into nvarchar column

Hi,

I have a problem with BULK INSERT. I created the following table:

Code Snippet

create table Test
(id char(4), name nvarchar(16), last char(1))

I am trying to bulk insert data from ASCII (not unicode) file with only two rows:

0011First name
0018Second name

Since it is a fixed length file, I am using the following format file:

Code Snippet

8.0
3
1 SQLCHAR 0 4 "" 1 ID HEBREW_CI_AS
2 SQLCHAR 0 16 "" 2 NAME HEBREW_CI_AS
3 SQLCHAR 0 0 "\r\n" 3 Last HEBREW_CI_AS

With bcp utility everything works just fine!

Code Snippet

bcp Demo.dbo.test in c:\test -T -f c:\test.fmt

But when I use BULK INSERT in the following form:

Code Snippet

BULK INSERT Test FROM 'c:\Test'
WITH
(
FORMATFILE='c:\Test.fmt',
CODEPAGE='OEM'
);

I am getting error

Server: Msg 4863, Level 16, State 1, Line 1
Bulk insert data conversion error (truncation) for row 1, column 2 (name).

Now, one interesting thing: if I change the name field from nvarchar to varchar, it is working with BULK INSERT as well.

Can anybody explain what is going on here?

I am using MS SQL 2000 and MSDE

Thanks in advance,

Eugene.

Another thing is that if I set the format file to specify row delimiter for that nvarchar field, it will also work.

Code Snippet

8.0
2
1 SQLCHAR 0 4 "" 1 ID HEBREW_CI_AS
2 SQLCHAR 0 16 "\r\n" 2 NAME HEBREW_CI_AS

But then in the real system i can't have multiple fields within the file...

|||

On SQL2005 the problem does not exist! Then it seems like a bug in SQL2000!

sql

Wednesday, March 28, 2012

Problem with blob field in SQL Server

In SQLServer database i have stored a blob using updateblob function,
type of the table column is image.
When i use Selectblob statement to get the blob into a blob variable, i am getting only 32 KB of data. But with ASA i am getting the complete data..
How to get Complete data in SQL Server?

regds.,
rangaWhich data provider are you using?

Terrisql

problem with bcp using format file

The running of my bcp (with queryout) is aborting, with the message below. A
t
first I identified that it happened only with column with NULL value, but no
w
I realize this occurrence happened in other field without NULL value.
Anyone has suggestions ? Thanks a lot
My format file has the following contents : 8.0 (version) 2 (number of
columns)
1 SQLCHAR 0 20 "\t" 1 numeroaj Latin1_General_CI_AS
2 SQLCHAR 0 54 "\r\n" 2 acervoespecializada Latin1_General_CI_AS
My bad run :
D:\Users\sql>bcp "SELECT numeroaj, acervoespecializada from
Siga.dbo.vwHerancaJa
cente" queryout C:\dts\hjacente.txt -f d:\users\sql\pgm3.fmt -Smyserver
-Umyuser -Pmypwd
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC SQL Server Driver]Erro de E/S ao ler o arquivo no
forma
to BCP ==> Translating... Error of I/O when read the format filewhere do you run this bcp statement, on the client or on the server itself.
"d:\" must be local to where ever you run the bcp statement.
-oj
"Adalberto Andrade" <Adalberto Andrade@.discussions.microsoft.com> wrote in
message news:014C3C25-592D-4A88-A320-325C52D49D2A@.microsoft.com...
> The running of my bcp (with queryout) is aborting, with the message below.
> At
> first I identified that it happened only with column with NULL value, but
> now
> I realize this occurrence happened in other field without NULL value.
> Anyone has suggestions ? Thanks a lot
> My format file has the following contents : 8.0 (version) 2 (number of
> columns)
> 1 SQLCHAR 0 20 "\t" 1 numeroaj Latin1_General_CI_AS
> 2 SQLCHAR 0 54 "\r\n" 2 acervoespecializada
> Latin1_General_CI_AS
> My bad run :
> D:\Users\sql>bcp "SELECT numeroaj, acervoespecializada from
> Siga.dbo.vwHerancaJa
> cente" queryout C:\dts\hjacente.txt -f d:\users\sql\pgm3.fmt -Smyserver
> -Umyuser -Pmypwd
> SQLState = S1000, NativeError = 0
> Error = [Microsoft][ODBC SQL Server Driver]Erro de E/S ao ler o arquivo no
> forma
> to BCP ==> Translating... Error of I/O when read the format file|||Hi oj,
On the client. And "d:\" is a local drive (in my machine). With
others columns it worked OK.
Thanks
Adalberto Andrade
"oj" wrote:

> where do you run this bcp statement, on the client or on the server itself
.
> "d:\" must be local to where ever you run the bcp statement.
> --
> -oj
>
> "Adalberto Andrade" <Adalberto Andrade@.discussions.microsoft.com> wrote in
> message news:014C3C25-592D-4A88-A320-325C52D49D2A@.microsoft.com...
>
>|||Adalberto,
Please check to see if there is a carriage return at the
end of your format file and that there are no extra tabs
or anything else in it. Also be sure the format file
is not open in an editor when you run the command.
The error message mentions the format file, not the
data file, so I think the problem is with the format file.
Steve Kass
Drew University
Adalberto Andrade wrote:
>Hi oj,
> On the client. And "d:\" is a local drive (in my machine). With
>others columns it worked OK.
>
> Thanks
> Adalberto Andrade
>
>
>"oj" wrote:
>
>|||Steve,
I made a complete revision of all components of my environment.
Things like : cr (carriage return), opened format file and others wrongs
caracters inside of format file are not the problem. I am thankful for yours
suggestions,but the problem continue. Now I substituted the third column of
my output file and the bcp utility started the copy, but the generated file
has mixed data with stranger caracters. This new column has valids datas and
also null values in some registers and it is the great difference between th
e
others columns (first e second ones). Without this third column everything
work 100% OK. I already try to change the value of prefix length (field of
the format file) to -1 or 2 with the hope to solve it, but the output
generated file continue with stranger and mixed caracters (like ASCII
caracters). I really don't have any idea of what I can do to put it to work.
I am not sure, but perhaps I will need to make other configuration in my
format file, but exactly what ? Do you have other help for me ?
Thanks again
Adalberto Andrade
"Steve Kass" wrote:

> Adalberto,
> Please check to see if there is a carriage return at the
> end of your format file and that there are no extra tabs
> or anything else in it. Also be sure the format file
> is not open in an editor when you run the command.
> The error message mentions the format file, not the
> data file, so I think the problem is with the format file.
> Steve Kass
> Drew University
> Adalberto Andrade wrote:
>
>|||Adalberto,
I am not sure what the problem is, but here are three separate
suggestions.
1. Try to use bcp without a format file, since TAB and NEWLINE
are the defaults for bcp. If this creates a Unicode file, you will need
to change the format file to say SQLNCHAR instead of SQLCHAR,
and you will also need to put the Unicode two-byte signature into
the beginning of the file yourself, since bcp does not do this for you.
2. Be sure the format file is saved as ASCII, not Unicode, then try
again with the format file.
3. Verify the data lengths and types of the output,
3A. Run this and provide the output.
select top 1
numeroaj, acervoespecializada
into CheckTypesTable
from Siga.dbo.vwHerancaJacente
select * from CheckTypesTable
3B. In Query Analyzer, refresh the current database
and for [CheckTypesTable] choose "Script Table To
New Window" to verify the data types of these columns
and provide the output.
3C. After doing this, you can DROP the table CheckTypesTable.
It might help if you post the definition of Siga.dbo.vwHerancaJa.
(If it is a view, also post CREATE TABLE statements from the
tables it uses for the columns numeroaj and acervoespecializada
(and the third column, since at one point you mention three columns.
Also, when you have three columns, what is your query?)
SK
Adalberto Andrade wrote:
>Steve,
> I made a complete revision of all components of my environment.
>Things like : cr (carriage return), opened format file and others wrongs
>caracters inside of format file are not the problem. I am thankful for your
s
>suggestions,but the problem continue. Now I substituted the third column of
>my output file and the bcp utility started the copy, but the generated file
>has mixed data with stranger caracters. This new column has valids datas an
d
>also null values in some registers and it is the great difference between t
he
>others columns (first e second ones). Without this third column everything
>work 100% OK. I already try to change the value of prefix length (field of
>the format file) to -1 or 2 with the hope to solve it, but the output
>generated file continue with stranger and mixed caracters (like ASCII
>caracters). I really don't have any idea of what I can do to put it to work
.
>I am not sure, but perhaps I will need to make other configuration in my
>format file, but exactly what ? Do you have other help for me ?
>
> Thanks again
>Adalberto Andrade
>"Steve Kass" wrote:
>
>|||Steve,
Forgive me for delay in my reply. I was very busy. Let 's go. Really
you are correct. When I ran the bcp utility in the prompt without my format
file, it show the message explaining that happened a truncate. In true there
was a difference between the data length of one column and your value define
d
for this size in the format file. Summarizing, the problem is over and your
suggesntions 1 and 3 were very helpful.
Thanks a lot
Adalberto
Andrade
Rio de Janeiro's
City Hall
"Steve Kass" wrote:

> Adalberto,
> I am not sure what the problem is, but here are three separate
> suggestions.
> 1. Try to use bcp without a format file, since TAB and NEWLINE
> are the defaults for bcp. If this creates a Unicode file, you will need
> to change the format file to say SQLNCHAR instead of SQLCHAR,
> and you will also need to put the Unicode two-byte signature into
> the beginning of the file yourself, since bcp does not do this for you.
> 2. Be sure the format file is saved as ASCII, not Unicode, then try
> again with the format file.
> 3. Verify the data lengths and types of the output,
> 3A. Run this and provide the output.
> select top 1
> numeroaj, acervoespecializada
> into CheckTypesTable
> from Siga.dbo.vwHerancaJacente
> select * from CheckTypesTable
> 3B. In Query Analyzer, refresh the current database
> and for [CheckTypesTable] choose "Script Table To
> New Window" to verify the data types of these columns
> and provide the output.
> 3C. After doing this, you can DROP the table CheckTypesTable.
>
> It might help if you post the definition of Siga.dbo.vwHerancaJa.
> (If it is a view, also post CREATE TABLE statements from the
> tables it uses for the columns numeroaj and acervoespecializada
> (and the third column, since at one point you mention three columns.
> Also, when you have three columns, what is your query?)
> SK
> Adalberto Andrade wrote:
>
>

Problem with Auto-increment of an ID

Hello,
I have a little problem with SQL Server 2005. I have chosen the option "auto-increment" for a column which includes the primary key. Moreover, I turned the option "Ignore double values" on. I get the datasets from a SSIS-Import-project. Unfortunately, the ID is getting incremented even if there are double values.
For example:
The first entries in the table have the IDs: 1, 2, 3, 4, 5
Then I start the SSIS-project which tries to write the first 5 entries again in the database. Of course, the entries do not appear again in the db but a new entry gets the ID 11 instead of 6. Is there a setting, that the ID won't get incremented if there double values?
Thanks
M-l-G

i dont't think its possible and when the column is primary key, it does not make sense also.

Madhu

Monday, March 26, 2012

Problem with ALTER TABLE in stored procedure

Hello,
I am trying to drop a column from a table with a stored procedure that
chacks if the column exists before droping it. However, I am having trouble
with passing the Table Name and Column Name to the ALTER TABLE command. The
code is:
CREATE PROCEDURE usp_DeleteColumnEx
@.TableName varchar(200),
@.ColumnName varchar(200)
AS
IF EXISTS
(SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
WHERE ObjectProperty(O.ID,'IsUserTable')= 1
AND O.Name = @.TableName
AND C.Name = @.ColumnName)
ALTER TABLE @.TableName DROP COLUMN @.ColumnName
When I try to execute this the server returns an error: "Incorrect syntax
near '@.TableName'". I am assuming that I cannot just pass the table name as
a
parameter. Is there a another way to do this?
Thank you for your help.
Daniel> ALTER TABLE @.TableName DROP COLUMN @.ColumnName
You can't do this - SQL Server has to know what objects you're talking
about. The best you could do is dynamic SQL, please read:
http://www.sommarskog.se/dynamic_sql.html
On a side note, why on earth are you changing your table structure on the
fly like this? Sounds very dangerous and suspicious, but not in the Austin
Powers way.|||"Daniel" <Daniel@.discussions.microsoft.com> wrote in message
news:9A9DCE9F-191A-4E76-AD5A-FC6E7A316E61@.microsoft.com...
> Hello,
> I am trying to drop a column from a table with a stored procedure that
> chacks if the column exists before droping it. However, I am having
> trouble
> with passing the Table Name and Column Name to the ALTER TABLE command.
> The
> code is:
> CREATE PROCEDURE usp_DeleteColumnEx
> @.TableName varchar(200),
> @.ColumnName varchar(200)
> AS
> IF EXISTS
> (SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
> WHERE ObjectProperty(O.ID,'IsUserTable')= 1
> AND O.Name = @.TableName
> AND C.Name = @.ColumnName)
> ALTER TABLE @.TableName DROP COLUMN @.ColumnName
> When I try to execute this the server returns an error: "Incorrect syntax
> near '@.TableName'". I am assuming that I cannot just pass the table name
> as a
> parameter. Is there a another way to do this?
> Thank you for your help.
> Daniel
Why would you want a proc that drops columns? Help me understand what you
are trying to achieve.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Aaron and David,
Thank you for your replies. The reason I need to alter the table dynamically
is
that I have a table where each record is corresponds to one employee, each
column represents a different skill involved in the employees' everyday work
.
In each column every employee have assigned a number corresponding to their
skill level. According to their skills they are assigned to their work
stations, which is VERY important for the management.
This is a basically how the table looks like:
Create table SkillsCheck (
emp_id int,
skill1 int,
skill2 int,
skill3 int,
skill4 int)
The problem is that the company has the option to change what skills they
want to track, so when that happens I have to drop or add a column to the
table to reflect the current situation. For example, they might decide that
they do not want to track skill3 anymore, but want to track skill5, so my
program needs to drop skill3 column and add skill5 column. I am working with
VB.NET and I can execute the ALTER TABLE statement from my code, but I think
that it would be better to use stored procedure that check if the column
exists before adding or droping.
After considering the situation I decided that would be easier to alter the
table instead of keeping the information in multiple tables. If you have
encountered a similiar scenario maybe you can give me an advice for more
efficient approach to this problem.
Thank you for your help,
Daniel
"Daniel" wrote:

> Hello,
> I am trying to drop a column from a table with a stored procedure that
> chacks if the column exists before droping it. However, I am having troubl
e
> with passing the Table Name and Column Name to the ALTER TABLE command. Th
e
> code is:
> CREATE PROCEDURE usp_DeleteColumnEx
> @.TableName varchar(200),
> @.ColumnName varchar(200)
> AS
> IF EXISTS
> (SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
> WHERE ObjectProperty(O.ID,'IsUserTable')= 1
> AND O.Name = @.TableName
> AND C.Name = @.ColumnName)
> ALTER TABLE @.TableName DROP COLUMN @.ColumnName
> When I try to execute this the server returns an error: "Incorrect syntax
> near '@.TableName'". I am assuming that I cannot just pass the table name a
s a
> parameter. Is there a another way to do this?
> Thank you for your help.
> Daniel|||Daniel wrote:
> Aaron and David,
> Thank you for your replies. The reason I need to alter the table dynamical
ly
> is
> that I have a table where each record is corresponds to one employee, each
> column represents a different skill involved in the employees' everyday wo
rk.
> In each column every employee have assigned a number corresponding to thei
r
> skill level. According to their skills they are assigned to their work
> stations, which is VERY important for the management.
> This is a basically how the table looks like:
> Create table SkillsCheck (
> emp_id int,
> skill1 int,
> skill2 int,
> skill3 int,
> skill4 int)
> The problem is that the company has the option to change what skills they
> want to track, so when that happens I have to drop or add a column to the
> table to reflect the current situation. For example, they might decide tha
t
> they do not want to track skill3 anymore, but want to track skill5, so my
> program needs to drop skill3 column and add skill5 column. I am working wi
th
> VB.NET and I can execute the ALTER TABLE statement from my code, but I thi
nk
> that it would be better to use stored procedure that check if the column
> exists before adding or droping.
> After considering the situation I decided that would be easier to alter th
e
> table instead of keeping the information in multiple tables. If you have
> encountered a similiar scenario maybe you can give me an advice for more
> efficient approach to this problem.
> Thank you for your help,
> Daniel
>
> "Daniel" wrote:
>
The type of relationship between employees and skills is called
many-to-many. The textbook solution looks like this:
CREATE TABLE EmployeeSkills
(emp_id INTEGER NOT NULL
REFERENCES Employees (emp_id),
skill_code INTEGER NOT NULL
REFERENCES Skills (skill_code),
PRIMARY KEY (emp_id,skill_code));
This has huge advantages over the design that you proposed: It can
support any number of skills. No redundancy. No nulls required. Joins
and queries always reference just one skills column. The table
structure doesn't ever need to change (!).
I recommend you read up and study some relational design theory. Most
database architects would consider your suggestion as a serious design
flaw. To appreciate why you need to understand principles like
normalization and the normal forms, which are some of the tools we use
to design effective databases.
Hope this helps.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||As you stated, it would take a schema changed to accommodate future
requirements. Such as that, you're better off by creating a skills table to
store the skills. Any changes will just be a simple delete from the tables.
Also, this approach will not incur a table lock like you have when doing
schema update.
e.g.
create table skills(skillid int primary key, skillname sysname)
create table skillscheck(empid int primary key, skillid int foreign key
references skills(skillid))
-oj
"Daniel" <Daniel@.discussions.microsoft.com> wrote in message
news:3505642D-711F-43F6-8D73-DA004C791B34@.microsoft.com...
> Aaron and David,
> Thank you for your replies. The reason I need to alter the table
> dynamically
> is
> that I have a table where each record is corresponds to one employee, each
> column represents a different skill involved in the employees' everyday
> work.
> In each column every employee have assigned a number corresponding to
> their
> skill level. According to their skills they are assigned to their work
> stations, which is VERY important for the management.
> This is a basically how the table looks like:
> Create table SkillsCheck (
> emp_id int,
> skill1 int,
> skill2 int,
> skill3 int,
> skill4 int)
> The problem is that the company has the option to change what skills they
> want to track, so when that happens I have to drop or add a column to the
> table to reflect the current situation. For example, they might decide
> that
> they do not want to track skill3 anymore, but want to track skill5, so my
> program needs to drop skill3 column and add skill5 column. I am working
> with
> VB.NET and I can execute the ALTER TABLE statement from my code, but I
> think
> that it would be better to use stored procedure that check if the column
> exists before adding or droping.
> After considering the situation I decided that would be easier to alter
> the
> table instead of keeping the information in multiple tables. If you have
> encountered a similiar scenario maybe you can give me an advice for more
> efficient approach to this problem.
> Thank you for your help,
> Daniel
>
> "Daniel" wrote:
>|||Correction. Don't forget to add a column for the skill level:
CREATE TABLE EmployeeSkills
(emp_id INTEGER NOT NULL
REFERENCES Employees (emp_id),
skill_code INTEGER NOT NULL
REFERENCES Skills (skill_code),
skill_level INTEGER NOT NULL
CHECK (skill_level BETWEEN 0 AND 10),
PRIMARY KEY (emp_id,skill_code));
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Thanks David,
I will follow your advice and will read about many-to-many relationships.
After reading more on Dynamic SQL, looks like it is not the best choice.
Thanks again,
Daniel
"David Portas" wrote:

> Correction. Don't forget to add a column for the skill level:
> CREATE TABLE EmployeeSkills
> (emp_id INTEGER NOT NULL
> REFERENCES Employees (emp_id),
> skill_code INTEGER NOT NULL
> REFERENCES Skills (skill_code),
> skill_level INTEGER NOT NULL
> CHECK (skill_level BETWEEN 0 AND 10),
> PRIMARY KEY (emp_id,skill_code));
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||OJ,
Thanks you your reply. Looks like I need to revise the database design and
reorganize the tables differently.
Best Regards,
Daniel
"oj" wrote:

> As you stated, it would take a schema changed to accommodate future
> requirements. Such as that, you're better off by creating a skills table t
o
> store the skills. Any changes will just be a simple delete from the tables
.
> Also, this approach will not incur a table lock like you have when doing
> schema update.
> e.g.
> create table skills(skillid int primary key, skillname sysname)
> create table skillscheck(empid int primary key, skillid int foreign key
> references skills(skillid))
>
> --
> -oj
>
> "Daniel" <Daniel@.discussions.microsoft.com> wrote in message
> news:3505642D-711F-43F6-8D73-DA004C791B34@.microsoft.com...
>
>

Friday, March 23, 2012

Problem with AddNew on SQL server in c++ 2003

Hello,
I created a very simple database with only one table (Records) and on
that table only one column (Category datatype nvarchar).
I am trying to use the AddNew ado example found on msnd but it always
inserts a null value instead of the value I am trying to insert.
All my HRESULTs say S_OK but the CategoryStatus is alway 3 (which is
null).
I am using UNICODE.
I can insert records just fine if I use the INSERT INTO command but I
am not having any luck with the AddNew API.
Can anyone help?
Here is my code:
class CJournalRecord :public CADORecordBinding
{
BEGIN_ADO_BINDING(CJournalRecord)
ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, Category, sizeof(Category),
CategoryStatus, TRUE)
END_ADO_BINDING()
public:
CString Category;
ULONG CategoryStatus;
};
HRESULT hr = S_OK;
_RecordsetPtr pRstEvents = NULL;
IADORecordBinding *picRs = NULL;
hr = pRstEvents.CreateInstance(__uuidof(Recordset));
if (hr != S_OK)
{
}
else
{
//the connection is already open
CJournalRecord newEvent;
hr = pRstEvents->Open(_T("Records"),_variant_t((IDispatch *)
connection, true),adOpenKeyset,adLockOptimistic,adCm
dTable);
//Open an IADORecordBinding interface pointer which we'll use for
Binding Recordset to a class
hr =
pRstEvents-> QueryInterface(__uuidof(IADORecordBindin
g),(LPVOID*)&picRs);
hr = picRs->BindToRecordset(&newEvent);
newEvent.Category = _T("SeeYou");
newEvent.CategoryStatus = adFldNull;
if(hr!=S_OK)
{
}
else
{
hr = picRs->AddNew(&newEvent);
int status = (int)newEvent.CategoryStatus;
//hr = pRstEvents->Update();
}
}Try creating a stored procedure and executing that. Using AddNew from the
middle tier is kinda hokey.
<roberta.coffman@.emersonprocess.com> wrote in message
news:1134768159.533377.64050@.g43g2000cwa.googlegroups.com...
> Hello,
> I created a very simple database with only one table (Records) and on
> that table only one column (Category datatype nvarchar).
> I am trying to use the AddNew ado example found on msnd but it always
> inserts a null value instead of the value I am trying to insert.
> All my HRESULTs say S_OK but the CategoryStatus is alway 3 (which is
> null).
> I am using UNICODE.
> I can insert records just fine if I use the INSERT INTO command but I
> am not having any luck with the AddNew API.
> Can anyone help?
> Here is my code:
> class CJournalRecord :public CADORecordBinding
> {
> BEGIN_ADO_BINDING(CJournalRecord)
> ADO_VARIABLE_LENGTH_ENTRY2(1, adVarChar, Category, sizeof(Category),
> CategoryStatus, TRUE)
> END_ADO_BINDING()
> public:
> CString Category;
> ULONG CategoryStatus;
> };
> HRESULT hr = S_OK;
> _RecordsetPtr pRstEvents = NULL;
> IADORecordBinding *picRs = NULL;
> hr = pRstEvents.CreateInstance(__uuidof(Recordset));
> if (hr != S_OK)
> {
> }
> else
> {
> //the connection is already open
> CJournalRecord newEvent;
> hr = pRstEvents->Open(_T("Records"),_variant_t((IDispatch *)
> connection, true),adOpenKeyset,adLockOptimistic,adCm
dTable);
> //Open an IADORecordBinding interface pointer which we'll use for
> Binding Recordset to a class
> hr =
> pRstEvents-> QueryInterface(__uuidof(IADORecordBindin
g),(LPVOID*)&picRs);
> hr = picRs->BindToRecordset(&newEvent);
> newEvent.Category = _T("SeeYou");
> newEvent.CategoryStatus = adFldNull;
> if(hr!=S_OK)
> {
> }
> else
> {
> hr = picRs->AddNew(&newEvent);
> int status = (int)newEvent.CategoryStatus;
> //hr = pRstEvents->Update();
> }
> }
>|||I'm not sure binding to the CString Category works here, also
sizeof(Category) is pretty meaningless. Suggest you change
CString to a fixed sized array to mirror the size of the column
in your table, i.e. change
CString Category;
to
CHAR Category[80];

problem with a simple check

I know the answer to this is so obvious, I've done it before myself, but I
can't for the life of me get a check to work

I have a column called SaleOrRent which is char(1). all i want is to make
sure the only value that the column will accept is an S or an R

does this check have to be in the create table statementor can i add it
using the alter table statement?

Thanks
David (crap at SQL)

--
http://www.nintendo-europe.com/NOE/...=l&a=ProdigiousYou can do it either with CREATE or ALTER:

CREATE TABLE Sometable ( ... saleorrent CHAR(1) NOT NULL CONSTRAINT
CK_Sometable_saleorrent CHECK (saleorrent IN ('S','R')))

ALTER TABLE Sometable ADD CONSTRAINT CK_Sometable_saleorrent CHECK
(saleorrent IN ('S','R'))

--
David Portas
----
Please reply only to the newsgroup
--|||Thank you very much, works a treat

David

"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:t5Cdnd62y9us82CiRVn-hw@.giganews.com...
> You can do it either with CREATE or ALTER:
> CREATE TABLE Sometable ( ... saleorrent CHAR(1) NOT NULL CONSTRAINT
> CK_Sometable_saleorrent CHECK (saleorrent IN ('S','R')))
> ALTER TABLE Sometable ADD CONSTRAINT CK_Sometable_saleorrent CHECK
> (saleorrent IN ('S','R'))
> --
> David Portas
> ----
> Please reply only to the newsgroup
> --

Wednesday, March 21, 2012

Problem with a date function

Hello All!

I have a table with a date column. I would like to be able to DELETE the rows based on the date column. The condition is 30 days from todays date. So anything older than 30 days from todays date, it will delete those rows.

Any suggesttion the best way to do this. I was thinking of a simple select statement, but can't figure it out.

TIA!!

Rudy

Hi there,

Is your date column of data type DateTime? If so, try something like:

DELETE FROM [Table Name]
WHERE DATEADD(d, -30, GETDATE()) > [Date Column]

What happens is DATEADD(d, -30, GETDATE()) is used to obtain a date that is 30 days from todays date. Then, anything in the table where the entry in the Date Column (which I assume is of data type DateTime) is older than DATEADD(d, -30, GETDATE()), i.e. older than 30 days from today's date, gets deleted.

Hope that helps a bit, but sorry if it doesn't.
|||Thank you! Just what I needed!

Problem with [Left] in SQL Server 2005?

We have a table that contains a column named "Left". (Yea, I know, this was a bad idea - but it is not within my power to change it.)

Our stored procedures access it using [Left] without any problems in Sql Server 2000 and Sql Server Express Edition. HOWEVER, it does NOT work with SQL Server 2005. It generates the error: Column 'Left' is read-only.

Has anyone seen this? Is there a problem with SQL Server 2005 and reserved words using [ ] notation?

Thanks!

This is not a problem with the identifier (quoted or bracketed). The error message indicates that you are trying to modify the column using a query expression (CTE, view or derived table) and it is seen as read-only. Can you post a simple repro showing the problem? Or can you post the statement that is generating the error message.|||

We just tried running the stored procedure directly, and it works fine as well. So this must be a problem with ADO? Does that mean that I should be posting this question elsewhere? (Again, it works fine if we just reset the connection string to point to the database in SQL Server 2000 or SQL Server Express.)

This is a HUGE application that uses a form of the MS data block so it may be challenging (i.e. time consuming) to pull together a reasonably sized repro. But I'll see what I can get approval for ...

|||It could be something wrong in the client side. The client might be trying to update the query result (from query or view or SP). For example, you could be using wrong cursor type in the client code that might make the application think that a result is updateable. You could run a SQL Profiler trace to determine the statement from the client that is causing the error on the server. And there is no need to post the repro involving the client and the exact code. You should try to reproduce the problem independently using smaller set of tables and sample data. This is often the best way to isolate and understand the problem.|||

Found the problem. It had nothing to do with the [Left] actually. The stored procedure was doing a Union. The union seems to produce an updatable dataset in SQL Server 2000 and in SQL Server Express but NOT in Sql Server 2005.

Interesting ...

Problem with @@identity in SQL Server 6.5

In SQL Server 6.5, I have a table called employee
with two fields emp_id and emp_name where emp_id
is an identity column.

The below Stored Procedure is trying to select
the last inserted emp_id using @.@.identity.

CREATE PROCEDURE Employee AS

begin

SET IDENTITY_INSERT employee OFF

SET NOCOUNT ON

declare @.empid int

INSERT INTO employee(emp_name) VALUES
("Soundy")

SET @.empid = @.@.identity

return @.empid

end

But when compiling this procedure, SQL Server displays
an error saying "Incorrect syntax near @.empid".

Can i know where the problem is ?Q1 Can i know where the problem is ?

A1 Try 'Soundy' instead of "Soundy"? For example:

Use TempDB
Go

CREATE TABLE [employee] (
[emp_id] [int] IDENTITY (1, 1) NOT NULL ,
[emp_name] [nvarchar] (50) NULL)
Go

CREATE PROCEDURE ins_Employee
@.pEmpName nvarChar (50) AS
begin
SET IDENTITY_INSERT employee OFF
SET NOCOUNT ON
declare @.empid int
INSERT INTO employee(emp_name) VALUES
(@.pEmpName)
SET @.empid = @.@.identity
return @.empid
end

Go

DECLARE @.RC int
-- exec the Proc
EXEC @.RC = ins_Employee @.pEmpName = 'Soundy'
Select @.RC as '@.RC for ins_employee'
Go

SELECT emp_id, emp_name
FROM employee
Where
emp_id = (SELECT Max(emp_id)FROM employee)

Monday, March 12, 2012

Problem while giving Quarter function

Sir,

When I am giving the command like Quarter(DateOfOrder) in new named dimension expression column , one error is showing ' Quarter is not recognised built in function ' . Please help me to find out the quarter of Date of Order column..

Thanks in advance..

Regards

Polachan

You need to use an expression such as

DATEPART(quarter,DateOfOrder)

To get the result you require

|||

Dear Sir,

Thanks a lot

Sir Please can u give me a help for the following problem while deployment of the project

Error 4

When I am deploying the project I got the following error. Please help me sir


Errors in the OLAP storage engine: An error occurred while processing the 'Product Tran Header' partition of the 'Product Tran Header' measure group for the 'Test' cube from the productreport database. 0 0

I done the following steps

1. added new measure selecting new source table

2. selected one column dateoforder

3. Add new dimension as without using data source

4. selected server time dimension

5. Selected Year/Month/Quarter/date

6 Selected fiscal year

7.Selected dimension usage in cube desgn

8. selected time dimension and selected regular relation, Granulary attribute as Date

9. Measure group table 'Product tran header' new measure group

10 selected measure group column as dateoforder.

after that while deploying the above mentioned error will come

Please help

|||As far as I know, I answered your question. Why have you answered that with a completely different question ? |||

Sir,

I wan to know how to give relationship Servertime Dimension with the column in the table DateOfOreder. When I am giving this with the mentioned step I got the error. Please help me sir...

Friday, March 9, 2012

problem when inserting

I want to insert a recorde into my table (2 column) : name and Id

id is a primary key and this is the error MSG im getting everytime im trying to insert a record

Error:Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF.

what is the problem

here is the code :

protectedvoid Button2_Click(object sender,EventArgs e)

{

try

{

string str ="data source=.;integrated security=true; initial catalog=NH_Project2";

SqlConnection conn =newSqlConnection(str);

SqlCommand comm =newSqlCommand("insert into [Customer](Name,Id) values(@.custName,@.custId)", conn);

comm.CommandType =CommandType.Text;

comm.Parameters.AddWithValue("@.custName", TextBox1.Text);comm.Parameters.AddWithValue("@.custId", TextBox2.Text);

conn.Open();

int rowaff = (int)comm.ExecuteNonQuery();

if (rowaff == 1)

{

Label4.Visible =true;Label4.Text ="one customer has added to our data base";

}

else

{

Label4.Visible =false;Label4.Text ="not added try again";

}

}

catch (Exception ex)

{

Response.Write("Error:" + ex.Message);

}

}

You need to understand IDENTITY columns. Please read up books online. If you want to explicitly insert a value into it you need to use SET IDENTITY_INSERT <Table> ON before the INSERT and set it to OFF after the insert. IF you want to let SQL Server handle the Id's you should remove the column from your INSERT list so SQL Server can do it for you.

|||

"IF you want to let SQL Server handle the Id's you should remove the column from your INSERT list so SQL Server can do it for you."

how can I do that ? do you mean to call stored procedure and have it insert into that column?

thanks for your advice, any specific books that you would recommend ?

Tongue Tied

|||modify your command definition line to:SqlCommand comm = new SqlCommand("insert into [Customer](Name) values(@.custName)", conn); and pass only customer name parametercomm.Parameters.AddWithValue("@.custName", TextBox1.Text)IF you do this ID value will be assigned by database itselfIf you would like to use you logic you have to allow to insert identities into table by running:SqlCommand comm = new SqlCommand("SET IDENTITY_INSERT dbo.[customer] ON insert into [Customer](Name,Id) values(@.custName,@.custId) SET IDENTITY_INSERT dbo.[customer] OFF", conn); but you have to be sure that Identity you try to insert does not exists in table before you do insert.|||

No just remove it from your INSERT list..Just insert the name, the ID will be inserted by SQL Server.

insert into [Customer](Name) values(@.custName)"

|||

Yes

that was helpful

|||

The problem is that your IDENTITY COLUMN is inserted automatically! If so the only thing you need is:
insert into [Customer](Name) values(@.custName)

When inserted, the new Customer is given an ID automatically!

SuperJB

problem when insert DateTime to DataBase

the column type of stime and etime in Dabase both are datetime

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

public DateTime loginTime
{
get
{

//got user enter page's time
return DateTime.Now;
}

}

//record user's using time when user click exit button

protected void Button1_Click(object sender, EventArgs e)
{

int Member_No = Int32.Parse(cls_login2.GetCurrent_login_Member_no(this.Page));
int Lesson_No = Int32.Parse(Lesson_no);
int Prestep = 1;
string RemoteIp = Request.ServerVariables["REMOTE_ADDR"].ToString();

string sqlConn = "Insert into pro_Study_log (Member_no,Lesson_no,Study_log_stepid,Study_log_stime,Study_log_etime,Study_log_ip) ";
sqlConn += "values(" + Member_No + "," + Lesson_No + "," + Prestep + "," + loginTime + ", getdate(), '" + RemoteIp + "')";
SqlConnection connLog = new SqlConnection(StrConn);

SqlCommand cmdLog = new SqlCommand(sqlConn, connLog);
cmdLog.CommandType = CommandType.Text;
connLog.Open();
cmdLog.ExecuteNonQuery();
connLog.Close();

--------

and then I got error message on column Study_log_stime

I also trid set the dateimt tostring , still doesn't work..

I don't know where I did wrong... pleae help

many thanks

You need to put quotes around logintime. Also, I'd recommend using Parameterized Queries rather than concatenating strings. With what you have now there is a high potential for SQL Injection attacks.

|||

it's helpless if we just put quotes around logintime ( cause another error message)

problem has been resolved by use stored procedure...

thank you very much

Saturday, February 25, 2012

Problem using SELECT statement on Access Column Name

Im writing a VB program that queries an MS Access db. The column name is CONTACT#. Using the SQL statement...
"SELECT * FROM CLIENT WHERE CONTACT# = '1'"
Produces an error. I cannot change the name of the column name is there anyway around this?Try this:
SELECT * FROM CLIENT WHERE [CONTACT#] = '1'
:eek:

problem using ntext

Hi, I'm using a column(ntext) to store some long strings. An example of the string that I need to store is the following:

436;Implementing A Gang - Awareness Program/And A Middle SchoolGang Prevention Curriculum. Doctoral Th;Samuels;Donald J;MiamiIV;Administrators; At Risk; Child And Youth Studies; Community;Community Members; Drop Out Prevention; Educational Leadership;Law/Criminal Justice; Peer Counseling; Principals; Secondary Education

I wrote a store procedure that does it, but it seems that the columnspace is not enough for the above string. The string in fact, istruncated and only the following portion is stored in my table:

436;Implementing A Gang - Awareness Program/And A Middle School Gang Prevention Curriculum. Doctoral Th;Samuels;Donald J;MiamiIV;Administrators; At Risk; Child And Youth Studies; Community;Community Members; Drop Out Prevention; Educational Leadership

What can I do?

ChristianIf you are not storing more than 4000 characters you can use NVarChar 4000 is the limit. The reason there are issues with NText and limitations. Hope this helps.|||I have just changed the column type from text to varchar(4000).
But I still have the same problem.

Christian|||

Try the link below for working code sample. Hope this helps.

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.insertcommand.aspx

|||

christianmala:

I wrote a store procedure that does it, but it seems that the columnspace is not enough for the above string. The string in fact, istruncated and only the following portion is stored in my table:


How are you checking what is stsored in your table? I highly suspect you are using Query Analyzer, which by default will only display the first 256 characters in a column. To change this value in QA, Tools - Options - Results - Maximum characters per column. Change 256 to something larger.|||Oh God,
you are so right!!!!!

Thanks,

Christian

problem using LIKE in UNICODE characters...

I have a table with nVarchar column.

If i do a search like this
----------------------
SELECT ID, Book, Chapter, Number, Amharic, English
FROM tbl_test
WHERE (Amharic LIKE '%???%')

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

it doesn't return anything but if i add 'N' after LIKE as
----------------------
SELECT ID, Book, Chapter, Number, Amharic, English
FROM tbl_test
WHERE (Amharic LIKE N'%???%')

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

It returns the whole table without filtering.

Can someone help me with this?

What about this:

WHERE RTRIM(Amharic) LIKE '%???%'

Monday, February 20, 2012

Problem Using Alias

I need a select that sums the same column, but with different criteria.
I also need to "roll up" the sums into a "higher level" sum based on
some other tables. This is an accounting database, where subaccounts
roll up into a single account (i.e. subaccounts 101 and 102 roll up
into account 100).
I'm using an alias, but not getting correct results. I believe I'm
ending up with a cartesian product, but not sure of the "fix". Note: I
cannot change the table design, this is an existing accounting database
created by a different application.
Here's a simplified version of the query with tables following that:
SELECT Account.Name, Sum(A.Amount) as Actual, Sum(B.Amount) as Budget
FROM Account, SubAccount, Trans A, Trans B
WHERE
Account.AccountNum = SubAccount.AccountNum and
Trans.SubAccountNum = SubAccount.SubAccountNum and
A.Trans.Type = 'A' and B.Trans.Type = 'B'
GROUP BY Account.Name
What's wrong with my SQL above?
Here are my tables with sample data:
Table: Account
AccountNum Name
--
100 Fuel
200 Tires
Table: SubAccount
AccountNum SubAccountNum Name
---
100 101 Diesel
100 102 Gasoline
200 200 Winter Tire
200 201 All Season Tire
Table: Trans (transactions)
SubAccountNum Amount Type (A-Actual, B-Budget)
---
101 10 A
102 20 A
200 30 A
201 40 A
101 50 B
102 60 B
200 70 B
201 80 B

>From the data above, I need to end up with output from my Select as
follows:
Name Actual Budget
--
Fuel 30 110
Tires 70 150> FROM Account, SubAccount, Trans A, Trans B
Please use ANSI inner joins. It will make your query easier to read and
will allow you to

> Trans.SubAccountNum = SubAccount.SubAccountNum and
> A.Trans.Type = 'A' and B.Trans.Type = 'B'
You're saying, instead of calling Trans "Trans", let's call it "A". What do
you expect A.Trans to mean? Didn't you mean
A.SubAccountNum = SubAccount.SubAccountNum
AND
A.Type = 'A'
AND B.Type = 'B'
I have a better way to formulate the query however, because of my first
point, I have no idea whether two copies of the Trans table are required,
how they each relate to Account and SubAccount, and how the sums should be
generated. If you provide more details I'd be more than happy to write you
a more readable query. Please see: http://www.aspfaq.com/5006|||As you said, I should be using joins. The code below did the trick.
Thanks for your input.
SELECT Account.Name,
Sum(Case Trans.Type When 'A' Then Trans.Amount Else 0 End) as Actual,
Sum(Case Trans.Type When 'B' Then Trans.Amount Else 0 End) as Budget
FROM Account
INNER JOIN SubAccount
ON Account.AccountNum = SubAccount.AccountNum
INNER JOIN Trans
ON Trans.SubAccountNum = SubAccount.SubAccountNum|||> Please use ANSI inner joins. It will make your query easier to read and
> will allow you to
finish sentences! What I was going to elaborate on about is that you can
separate join and filter criteria. Looks like you've already got a handle
on it in this case.|||CREATE TABLE Accounts (AccountNum int NOT NULL, [name] varchar(25), PRIMARY
KEY (AccountNum))
GO
CREATE TABLE SubAccounts (AccountNum int REFERENCES Accounts(AccountNum),
SubAccountNum int, [name] varchar(25))
GO
INSERT INTO Accounts VALUES (100, 'Fuel')
INSERT INTO Accounts VALUES (200, 'Tires')
INSERT INTO SubAccounts VALUES (100,101,'Diesel')
INSERT INTO SubAccounts VALUES (100,102,'Gasoline')
INSERT INTO SubAccounts VALUES (200,200,'Winter Tire')
INSERT INTO SubAccounts VALUES (200,201,'All Season Tire')
CREATE TABLE Trans
(SubAccountNum int, Amount int, Type char(1))
GO
INSERT INTO test4 VALUES (101,10,'A')
INSERT INTO test4 VALUES (102,20,'A')
INSERT INTO test4 VALUES (200,30,'A')
INSERT INTO test4 VALUES (201,40,'A')
INSERT INTO test4 VALUES (101,50,'B')
INSERT INTO test4 VALUES (102,60,'B')
INSERT INTO test4 VALUES (200,70,'B')
INSERT INTO test4 VALUES (201,80,'B')
SELECT a.[name], SUM(t1.TotalActual) AS "Total Actual",
SUM(t2.TotalBudgeted) AS "Total Budgeted"
FROM Accounts a INNER JOIN SubAccounts sa ON a.AccountNum=sa.AccountNum
INNER JOIN (SELECT SubAccountNum, SUM(Amount) AS "TotalActual" FROM Trans
WHERE Type='A'
GROUP BY SubAccountNum) t1 ON t1.SubAccountNum=sa.SubAccountNum
INNER JOIN (SELECT SubAccountNum, SUM(Amount) AS "TotalBudgeted" FROM Trans
WHERE Type='B'
GROUP BY SubAccountNum) t2 ON t2.SubAccountNum=sa.SubAccountNum
GROUP BY a.[name]
"joeacunzo@.yahoo.com" wrote:

> I need a select that sums the same column, but with different criteria.
> I also need to "roll up" the sums into a "higher level" sum based on
> some other tables. This is an accounting database, where subaccounts
> roll up into a single account (i.e. subaccounts 101 and 102 roll up
> into account 100).
> I'm using an alias, but not getting correct results. I believe I'm
> ending up with a cartesian product, but not sure of the "fix". Note: I
> cannot change the table design, this is an existing accounting database
> created by a different application.
> Here's a simplified version of the query with tables following that:
> SELECT Account.Name, Sum(A.Amount) as Actual, Sum(B.Amount) as Budget
> FROM Account, SubAccount, Trans A, Trans B
> WHERE
> Account.AccountNum = SubAccount.AccountNum and
> Trans.SubAccountNum = SubAccount.SubAccountNum and
> A.Trans.Type = 'A' and B.Trans.Type = 'B'
> GROUP BY Account.Name
> What's wrong with my SQL above?
> Here are my tables with sample data:
> Table: Account
> AccountNum Name
> --
> 100 Fuel
> 200 Tires
> Table: SubAccount
> AccountNum SubAccountNum Name
> ---
> 100 101 Diesel
> 100 102 Gasoline
> 200 200 Winter Tire
> 200 201 All Season Tire
> Table: Trans (transactions)
> SubAccountNum Amount Type (A-Actual, B-Budget)
> ---
> 101 10 A
> 102 20 A
> 200 30 A
> 201 40 A
> 101 50 B
> 102 60 B
> 200 70 B
> 201 80 B
>
> follows:
> Name Actual Budget
> --
> Fuel 30 110
> Tires 70 150
>

problem updating text datatype

Hi All:
I am having trouble updating a TEXT column (I know that TEXT is a blob but I
am dealing with very large amounts of data that VARCHAR can not hold!) What
I want to happen is all rows from TableA that meet a certain criteria to be
inserted into TableB but if it already exists in TableB then update it
instead - this sounds simple enough and is working fine except that one of
the fields is TEXT datatype. So when I try to update I get an error "The
text, ntext, and image datatypes are invalid in this subquery or aggregate
expression." (Apparently you can not do an update select with a text
datatype) I did a search and found that I need to be using the UPDATETEXT
function - however I am not quite sure how this works. Any suggestions
would be greatly appreciated!
TableA
ID INT
MenuID INT
Content TEXT
TableB
ID INT
MenuID INT
Content TEXT
Thanks!Nancy,
Without seeing the query, it's impossible to know what the
problem is. Post the query that is causing the error, at
least, if you want a more specific answer.
In any case, it is certainly possible to update [text]
with an UPDATE statement. In general, you may want
something like this:
update TableB set
Content = TableA.Content
from TableA join TableB
on TableA.ID = TableB.ID
and TableA.MenuID = TableB.MenuID
insert into TableB(ID, MenuID, Content)
select ID, MenuID, Content
from TableA
where not exists (
select * from TableB as B2
where B2.ID = TableA.ID
and B2.MenuID = TableA.MenuID
)
Steve Kass
Drew University
Nancy Shelley wrote:

> Hi All:
> I am having trouble updating a TEXT column (I know that TEXT is a blob but
I
> am dealing with very large amounts of data that VARCHAR can not hold!) Wha
t
> I want to happen is all rows from TableA that meet a certain criteria to
be
> inserted into TableB but if it already exists in TableB then update it
> instead - this sounds simple enough and is working fine except that one of
> the fields is TEXT datatype. So when I try to update I get an error "The
> text, ntext, and image datatypes are invalid in this subquery or aggregate
> expression." (Apparently you can not do an update select with a text
> datatype) I did a search and found that I need to be using the UPDATETEXT
> function - however I am not quite sure how this works. Any suggestions
> would be greatly appreciated!
>
> TableA
> ID INT
> MenuID INT
> Content TEXT
> TableB
> ID INT
> MenuID INT
> Content TEXT
> Thanks!
>|||Hi Steve:
Thanks for the quick response. Supplying BLOB columns with text or image
data that's less than or equal to 8000 bytes in size is as straightforward
as updating any other type of column (you can use insert/update) but when
values are larger than 8000 you need to use updatetext or writetext. This
is what I was having trouble with - I know the syntax for updating my table
the regular way I just wasn't sure about using updatetext or writetext.
I ended up solving my own problem - my pointer was invalid. I was getting
an invalid pointer reference to the text column.
Thanks for your help!
Nancy
"Steve Kass" <skass@.drew.edu> wrote in message
news:OqsmT2jWFHA.3488@.tk2msftngp13.phx.gbl...
> Nancy,
> Without seeing the query, it's impossible to know what the
> problem is. Post the query that is causing the error, at
> least, if you want a more specific answer.
> In any case, it is certainly possible to update [text]
> with an UPDATE statement. In general, you may want
> something like this:
>
> update TableB set
> Content = TableA.Content
> from TableA join TableB
> on TableA.ID = TableB.ID
> and TableA.MenuID = TableB.MenuID
> insert into TableB(ID, MenuID, Content)
> select ID, MenuID, Content
> from TableA
> where not exists (
> select * from TableB as B2
> where B2.ID = TableA.ID
> and B2.MenuID = TableA.MenuID
> )
> Steve Kass
> Drew University
> Nancy Shelley wrote:
>|||Nancy,
I believe the syntax I suggested works for any length [text] or
[image] column.
You can also update or insert data into a text or image column if you
provide
it as a literal string or binary value. The 8000 byte limit does not
apply to
literals.
SK
Nancy Shelley wrote:

>Hi Steve:
>Thanks for the quick response. Supplying BLOB columns with text or image
>data that's less than or equal to 8000 bytes in size is as straightforward
>as updating any other type of column (you can use insert/update) but when
>values are larger than 8000 you need to use updatetext or writetext. This
>is what I was having trouble with - I know the syntax for updating my tabl
e
>the regular way I just wasn't sure about using updatetext or writetext.
>I ended up solving my own problem - my pointer was invalid. I was getting
>an invalid pointer reference to the text column.
>Thanks for your help!
>Nancy
>"Steve Kass" <skass@.drew.edu> wrote in message
>news:OqsmT2jWFHA.3488@.tk2msftngp13.phx.gbl...
>
>
>