Showing posts with label variables. Show all posts
Showing posts with label variables. Show all posts

Tuesday, March 27, 2012

Configuration files and variables

Hi ..

I need some information on the package configuration files. i.e how to set the configuration parameters from outside the packages. Pls provide me some detailed information along with examples. I want to make my packages to read paramaters from the configuration files as we have in .NET(web.config)////

Secondly I want to know how to play well with variables.. i.e setting a variable.. reading a variable.. passing a variable in the SSIS package dataflows and datatasks.. respectively. Please provide some infomation and a good exam[ple on it I need

sam_idea wrote:

Hi ..

I need some information on the package configuration files. i.e how to set the configuration parameters from outside the packages. Pls provide me some detailed information along with examples. I want to make my packages to read paramaters from the configuration files as we have in .NET(web.config)////

Have you looked in BOL? There's plenty in there regarding SSIS configurations.

Example here: http://www.sqlis.com/?26

sam_idea wrote:

Secondly I want to know how to play well with variables.. i.e setting a variable.. reading a variable.. passing a variable in the SSIS package dataflows and datatasks.. respectively. Please provide some infomation and a good exam[ple on it I need

The 2 most common methods for setting the value of a variable are using an expression (when the variable has EvaluateAsExpression=TRUE, example here: http://blogs.conchango.com/jamiethomson/archive/2005/03/19/1163.aspx) or a script task. There are various tasks (e.g. Execute SQL Task, XML Task) and components (e.g. Rowcount transform, Recordset destination) that can set variable values also.

There is no concept of "passing variables between tasks". A variable is scoped to a container within the package and is accessible by that container and all its ancestral containers. You can pass values between tasks by storing them in variables (note the subtle difference here)

Here's some examples of how you can use variables:

http://blogs.conchango.com/jamiethomson/archive/2005/07/04/1748.aspx

http://blogs.conchango.com/jamiethomson/archive/2005/04/09/1265.aspx

http://blogs.conchango.com/jamiethomson/archive/2005/06/15/1693.aspx

http://blogs.conchango.com/jamiethomson/archive/2005/05/30/1489.aspx

http://blogs.conchango.com/jamiethomson/archive/2005/02/09/964.aspx

Here's a tip for you. Google is your friend and alot quicker than this forum: http://www.google.co.uk/search?hl=en&q=ssis+configurations&meta=

-Jamie

Tuesday, March 20, 2012

conditional WHERE sections.

Hi I have a query where I am reading in a bunch of veriables and only want to
run parts of the where clause if the variables are valid, (will be input in a
stored procedure)
I tried
WHERE
if @.var1 IS NULL
BEGIN
{
tablename.fieldname >= @.var1
}
END
if @.var2 IS NULL
BEGIN
{
AND tablename.fieldname >= @.var2
}
END
[Microsoft][ODBC SQL Server Driver]Syntax error or access violation occures
thanks.
Paul G
Software engineer.
Paul
Create a dynamic SQL statement and build the where clause. Then execute the
SQL statement:
declare @.sql varchar(8000)
set @.sql = 'select * from table where '
If @.var1 is null
set @.sql = @.sql + 'condition 1'
else
set @.sql = @.sql + 'condition 2'
exec @.sql
"Paul" wrote:

> Hi I have a query where I am reading in a bunch of veriables and only want to
> run parts of the where clause if the variables are valid, (will be input in a
> stored procedure)
> I tried
> WHERE
> if @.var1 IS NULL
> BEGIN
> {
> tablename.fieldname >= @.var1
> }
> END
> if @.var2 IS NULL
> BEGIN
> {
> AND tablename.fieldname >= @.var2
> }
> END
> [Microsoft][ODBC SQL Server Driver]Syntax error or access violation occures
> thanks.
>
> --
> Paul G
> Software engineer.
|||There are several approaches for handling such requirements. Some of the
popular ones are detailed at: http://www.sommarskog.se/dyn-search.html
Anith
|||Hi thanks for the information. Figured there may be several ways to the
solution.
"Anith Sen" wrote:

> There are several approaches for handling such requirements. Some of the
> popular ones are detailed at: http://www.sommarskog.se/dyn-search.html
> --
> Anith
>
>
|||Ok looks like the dynamic SQL statement should work for what I am trying to
do. Thanks.
"Bruce" wrote:
[vbcol=seagreen]
> Paul
> Create a dynamic SQL statement and build the where clause. Then execute the
> SQL statement:
> declare @.sql varchar(8000)
> set @.sql = 'select * from table where '
> If @.var1 is null
> set @.sql = @.sql + 'condition 1'
> else
> set @.sql = @.sql + 'condition 2'
> exec @.sql
>
> "Paul" wrote:

Thursday, March 8, 2012

conditional logic in stored procedure

Hello.

Looking for a smarter way to code the following. I have a stored
procedure I will be passing several variables to. Some times, some of
the fields used in a WHERE clause will not be passed, and I would like
to avoid having to code a bunch of if statements to set the executing
code. For example, below I would only like to execute the LIKE
conditions only when the variable in question is not NULL. I did a
test and if the variable is set to null, obviously the select does not
return what I'm expecting.

if @.switch = "B"
SELECT * from ikb where
ikbtitle like @.ins1 and
ikbtitle like @.ins2 and
ikbtitle not like @.ins3 and
ikbbody like @.ins1 and
ikbbody like @.ins2 and
ikbbody not like @.ins3
end

Thanks for any help or information with this.>> I would only like to execute the LIKE conditions only when the
variable in question is not NULL. I did a test and if the variable is
set to null, obviously the select does not return what I'm expecting.
<<

SELECT *
FROM Foobar
WHERE kbtitle LIKE COALESCE(@.ins1, kbtitle)
AND ikbtitle LIKE COALESCE(@.ins2, ikbtitle)
AND ikbtitle NOT LIKE COALESCE(@.ins3, '')
AND ikbbody LIKE COALESCE(@.ins1, ikbbody)
AND ikbbody LIKE COALESCE(@.ins2, ikbbody)
AND ikbbody NOT LIKE COALESCE(@.ins3,'')|||Hi Jason,

Here's one suggestion. Change your params to '%' if they're null.
That way you don't need the IF statement. I would also rewrite the
"not like" clause as it's CPU intensive. - Louis

select @.ins1=isnull(@.ins1,'%')
select @.ins2=isnull(@.ins2,'%')
select @.ins3=isnull(@.ins3,'%')

SELECT * from ikb where
ikbtitle like @.ins1 and
ikbtitle like @.ins2 and
ikbtitle not like @.ins3 and
ikbbody like @.ins1 and
ikbbody like @.ins2 and
ikbbody not like @.ins3

Saturday, February 25, 2012

conditional dynamic SQL in stored procedure, not returning any result

Created a stored procedure which returns Selected table from database.

I pass variables,according to conditions

For some reason it is not returning any result for any condition

Stored Procedure

ALTER PROCEDUREdbo.StoredProcedure

(

@.conditionvarchar(20),

@.IDbigint,

@.date1as datetime,

@.date2as datetime

)

AS

/* SET NOCOUNT ON */

IF@.conditionLIKE'all'

SELECT CllientEventDetails.*

FROM CllientEventDetails

WHERE (ClientID = @.ID)

IF@.conditionLIKE'current_events'

SELECT ClientEventDetails.*

FROM ClientEventDetails

WHERE (ClientID = @.ID)AND

(EventFrom <=ISNULL(@.date1, EventFrom))AND

(EventTill >=ISNULL(@.date1, EventTill))

IF@.conditionLIKE'past_events'

SELECT ClientEventDetails.*

FROM ClientEventDetails

WHERE (ClientID = @.ID)AND

(EventTill <=ISNULL(@.date1, EventTill))

IF@.conditionLIKE'upcoming_events'

SELECT ClientEventDetails.*

FROM ClientEventDetails

WHERE(ClientID = @.ID)AND

(EventFrom >=ISNULL(@.date1, EventFrom))

IF@.conditionLIKE''

SELECT CllientEventDetails.*

FROM CllientEventDetails

RETURN

Also I would like to find out if I can put only "where" clause in if condition as my select statements are constants

Hi,

Please check whether the @.condition parameter you have provided can hit in the IF statements. At the end, you don't need to use RETURN if you don't return anything.

I would not suggest you put the condition in your WHERE clause, because it will return an empty result set for the condition that does not meet. And multiple result sets will be returned for all the SELECT statements.

|||

Nitin Pawar:

Created a stored procedure which returns Selected table from database.

I pass variables,according to conditions

For some reason it is not returning any result for any condition

Stored Procedure

ALTER PROCEDUREdbo.StoredProcedure

(

@.conditionvarchar(20),

@.IDbigint,

@.date1as datetime,

@.date2as datetime

)

AS

/* SET NOCOUNT ON */

IF@.conditionLIKE'all'

SELECT CllientEventDetails.*

FROM CllientEventDetails

WHERE (ClientID = @.ID)

IF@.conditionLIKE'current_events'

SELECT ClientEventDetails.*

FROM ClientEventDetails

WHERE (ClientID = @.ID)AND

(EventFrom <=ISNULL(@.date1, EventFrom))AND

(EventTill >=ISNULL(@.date1, EventTill))

IF@.conditionLIKE'past_events'

SELECT ClientEventDetails.*

FROM ClientEventDetails

WHERE (ClientID = @.ID)AND

(EventTill <=ISNULL(@.date1, EventTill))

IF@.conditionLIKE'upcoming_events'

SELECT ClientEventDetails.*

FROM ClientEventDetails

WHERE(ClientID = @.ID)AND

(EventFrom >=ISNULL(@.date1, EventFrom))

IF@.conditionLIKE''

SELECT CllientEventDetails.*

FROM CllientEventDetails

RETURN

Also I would like to find out if I can put only "where" clause in if condition as my select statements are constants

replaceLike by= and then try .. hope it will help

Tuesday, February 14, 2012

Concetenate variable in sp_executesql

Hi

I am trying to cinstruct two strings/variables and conetenate it in sp_executsql

Isnt this the right way to do it ?

CREATE PROCEDURE dbo.XML_Final

(

@.Filepath varchar(50),

@.DBName varchar(20))

AS

DECLARE @.hdoc int

DECLARE @.doc varchar(max)

--DECLARE @.doca varchar(max)

--DECLARE @.SQL nvarchar(200)

DECLARE @.INSERT nvarchar(max)

DECLARE @.WITH nvarchar(max)

SET @.SQL = N'select @.doc = c from OpenRowset(BULK''' + @.Filepath + N''', SINGLE_CLOB) as T(c)'

exec sp_executesql @.SQL, N'@.doc varchar(max) output' ,@.doc OUTPUT

EXECsp_xml_preparedocument @.hdoc OUTPUT, @.doc

SELECT @.INSERT = N' INSERT INTO'+ @.DBName + N'.dbo.Student( Name,Age,Address)'

--SET @.WITH = N @.TEMP1

SELECT @.WITH = N' SELECT * FROM OPENXML (@.hdoc,'+N'''/Name/Age'/Address+N''')' +N'

WITH

(

Name text'+ N' ' + '''http://Name' + N ''',

Age int' + ' ' + N'''http://Age+ N''',

Address int'+ ' ' + N'''http://Address'+ N'''

)'

exec sp_executesql @.INSERT+@.WITH

-- Remove the internal representation.

EXEC sp_xml_removedocument @.hdoc

Gives me a error at

exec sp_executesql @.INSERT+@.WITH :

Incorrect syntax near '+'

Thanks

You cannot concatenate the input variables like that. Try:

CREATE PROCEDURE dbo.XML_Final

(

@.Filepath varchar(50),

@.DBName varchar(20))

AS

DECLARE @.hdoc int

DECLARE @.doc varchar(max)

--DECLARE @.doca varchar(max)

--DECLARE @.SQL nvarchar(200)

DECLARE @.INSERT nvarchar(max)

DECLARE @.WITH nvarchar(max)

SET @.SQL = N'select @.doc = c from OpenRowset(BULK''' + @.Filepath + N''', SINGLE_CLOB) as T(c)'

exec sp_executesql @.SQL, N'@.doc varchar(max) output' ,@.doc OUTPUT

EXECsp_xml_preparedocument @.hdoc OUTPUT, @.doc

SELECT @.INSERT = N' INSERT INTO'+ @.DBName + N'.dbo.Student( Name,Age,Address)'

--SET @.WITH = N @.TEMP1

SELECT @.WITH = N' SELECT * FROM OPENXML (@.hdoc,'+N'''/Name/Age'/Address+N''')' +N'

WITH

(

Name text'+ N' ' + '''http://Name' + N ''',

Age int' + ' ' + N'''http://Age+ N''',

Address int'+ ' ' + N'''http://Address'+ N'''

)'

set @.SQL = @.INSERT + @.WITH

exec sp_executesql @.SQL, N'@.hdoc int', @.hdoc

-- Remove the internal representation.

EXEC sp_xml_removedocument @.hdoc

Sunday, February 12, 2012

Concatinating Variables

Hello,

How do I concatinate a variable. Here's the scenarios:

declare @.var1 varchar(20)
declare @.var2 varchar(20)
declare @.var3 varchar(20)
declare @.var4 varchar(20)
..
..
declare @.var32 varchar(20)

set @.var1 = 'Something 1'
set @.var2 = 'Something 2'
...
set @.var32 = 'Something 3'

/* I have to store the values of these individual variables. I wish to
have a "While" routine which iterates through the above variables. I
wish to have the variable name concatinated as that I do not have to
write numerous lines of code setting up individual 32 variables. How
could I use the '+' operator to join 'var' + @.count . Where count is
from 1 through 32. I am having some trouble with the syntax.*/

Regards,
VS[posted and mailed, please reply in news]

TinTin (lalalulu24@.yahoo.com) writes:
> How do I concatinate a variable. Here's the scenarios:
> declare @.var1 varchar(20)
> declare @.var2 varchar(20)
> declare @.var3 varchar(20)
> declare @.var4 varchar(20)
> .
> .
> declare @.var32 varchar(20)
> set @.var1 = 'Something 1'
> set @.var2 = 'Something 2'
> ...
> set @.var32 = 'Something 3'

SELECT @.concat = @.var1 + @.var2 + ... + @.var32

> /* I have to store the values of these individual variables. I wish to
> have a "While" routine which iterates through the above variables. I
> wish to have the variable name concatinated as that I do not have to
> write numerous lines of code setting up individual 32 variables. How
> could I use the '+' operator to join 'var' + @.count . Where count is
> from 1 through 32. I am having some trouble with the syntax.*/

Nah, you don't have a syntax problem, you have a mindset problem. When
you work in T-SQL, looping is something you don't do that often. This
is a very different language from VB or C++.

While T-SQL does have some looping constructs, normally you operate on
sets of data at a time through tables. While this may be more difficult
to grok initially, this is necessity to get performance with any size
of data volume.

Since I don't know why you have these 32 variables, and what your actual
business problem is, I cannot really tell what you should do instead.
But you should probably not concatenate 32 variables.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Hi

You will probably run into scope problems with this approach.

There seems to be a design issue here, but without knowing more about the
table strucures and what you are actually trying to do it is hard to suggest
a better solution other than hard coding each one or (as per your previous
post) look at using a temporary tables.

John

"TinTin" <lalalulu24@.yahoo.com> wrote in message
news:2d5425d1.0406151243.3bf0165a@.posting.google.c om...
> Hello,
> How do I concatinate a variable. Here's the scenarios:
> declare @.var1 varchar(20)
> declare @.var2 varchar(20)
> declare @.var3 varchar(20)
> declare @.var4 varchar(20)
> .
> .
> declare @.var32 varchar(20)
> set @.var1 = 'Something 1'
> set @.var2 = 'Something 2'
> ...
> set @.var32 = 'Something 3'
> /* I have to store the values of these individual variables. I wish to
> have a "While" routine which iterates through the above variables. I
> wish to have the variable name concatinated as that I do not have to
> write numerous lines of code setting up individual 32 variables. How
> could I use the '+' operator to join 'var' + @.count . Where count is
> from 1 through 32. I am having some trouble with the syntax.*/
> Regards,
> VS|||Hello John and Erland,

Thankyou for replying to my message.

As a matter or fact I have total of 52 variables.

These values are stored in an Excel spreadsheet. I use the DTS service
to import this spreadsheet into a temp table in SQL Server. Now I need
to catch these 53 different numeric values and parse them into
appropriate tabels in my Database. I use the Cursor to traverse
through the records in temp table and all these 53 values are Fetched
in 1 single record.

Hope this helps.

Regards!

"John Bell" <jbellnewsposts@.hotmail.com> wrote in message news:<VbLzc.1167$hb6.9819346@.news-text.cableinet.net>...
> Hi
> You will probably run into scope problems with this approach.
> There seems to be a design issue here, but without knowing more about the
> table strucures and what you are actually trying to do it is hard to suggest
> a better solution other than hard coding each one or (as per your previous
> post) look at using a temporary tables.
> John
> "TinTin" <lalalulu24@.yahoo.com> wrote in message
> news:2d5425d1.0406151243.3bf0165a@.posting.google.c om...
> > Hello,
> > How do I concatinate a variable. Here's the scenarios:
> > declare @.var1 varchar(20)
> > declare @.var2 varchar(20)
> > declare @.var3 varchar(20)
> > declare @.var4 varchar(20)
> > .
> > .
> > declare @.var32 varchar(20)
> > set @.var1 = 'Something 1'
> > set @.var2 = 'Something 2'
> > ...
> > set @.var32 = 'Something 3'
> > /* I have to store the values of these individual variables. I wish to
> > have a "While" routine which iterates through the above variables. I
> > wish to have the variable name concatinated as that I do not have to
> > write numerous lines of code setting up individual 32 variables. How
> > could I use the '+' operator to join 'var' + @.count . Where count is
> > from 1 through 32. I am having some trouble with the syntax.*/
> > Regards,
> > VS|||Also:

53 values is the worse case scenario. Total number of variables could
be 3 to 53. Script needs to check how many total variables there are
and then likewise take action.
"John Bell" <jbellnewsposts@.hotmail.com> wrote in message news:<VbLzc.1167$hb6.9819346@.news-text.cableinet.net>...
> Hi
> You will probably run into scope problems with this approach.
> There seems to be a design issue here, but without knowing more about the
> table strucures and what you are actually trying to do it is hard to suggest
> a better solution other than hard coding each one or (as per your previous
> post) look at using a temporary tables.
> John
> "TinTin" <lalalulu24@.yahoo.com> wrote in message
> news:2d5425d1.0406151243.3bf0165a@.posting.google.c om...
> > Hello,
> > How do I concatinate a variable. Here's the scenarios:
> > declare @.var1 varchar(20)
> > declare @.var2 varchar(20)
> > declare @.var3 varchar(20)
> > declare @.var4 varchar(20)
> > .
> > .
> > declare @.var32 varchar(20)
> > set @.var1 = 'Something 1'
> > set @.var2 = 'Something 2'
> > ...
> > set @.var32 = 'Something 3'
> > /* I have to store the values of these individual variables. I wish to
> > have a "While" routine which iterates through the above variables. I
> > wish to have the variable name concatinated as that I do not have to
> > write numerous lines of code setting up individual 32 variables. How
> > could I use the '+' operator to join 'var' + @.count . Where count is
> > from 1 through 32. I am having some trouble with the syntax.*/
> > Regards,
> > VS|||> through the records in temp table and all these 53 values are Fetched
> in 1 single record.

This sounds like a design problem too. Column values should be atomic values
not concatenated strings. On the other hand, 53 columns representing a list
of values seems unlikely to be the right design either: "Lists" are
analogous to *tables* not a set of values in a row.

Are you familiar with the concept of Normalization? Are you sure your
database is in at least Third Normal Form? If you don't have the correct
design to start with then you won't have the right foundation to build
concise, efficient and maintainable code and you'll have to struggle with
lots of cursors, loops and variables.

On the other hand, if you've already properly identified the entities and
attributes in your schema then post your CREATE TABLE statements so that we
can understand the problem and suggest how to tacke it.

Hope this helps.

--
David Portas
SQL Server MVP
--|||The table which I talk about is a temporary table which is created
within the procedure and would be deleted once I leave the stored
procedure. The sole purpose of the table would be to catch the values
from a seperate table which is extracted from Excel spreadsheet. It's
not dependent on any of the other tables in the database. Hence,
haven't looked upon Normalizing.

Here's the sample lines from the spreadsheet.I used the DTS to import
this into the database table.

Country Nigeria
Region African Continent
Gender Male Male Male Male Male Female
Female ...
Age Group 0-10 10-20 20-30 40-50 50-60 0-10
10-20 ...
Total 200 323 111 3232 333 555 333
..
..
..

Country Nicragua
Region African Continent
Gender Male Male Male Female Female Female
Age Group 0-4 15-20 20-30 0-4 15-20 20-30
Total 200 323 111 3232 112 441
..
..
..

Now... Age group can have several more or a lot fewer age categories.
I need to capture the individual values in the 'Age Group' and
'Total'. That is why I need to have 53 variables (Worst Case). I use a
Cursor to iterate through each of the above lines. Once I capture the
information, I need to send it to my database structure.

What's the best way to design a Stored Procedure. Messier way is to
have 53 varbs. (worst case) and have 2 tempory tables to store the
above 2 rows (Age Group, Total). If I follow this approach, I need to
iterate through the fields in the temporary variables to make sure I
do not encounter any NULLs in between. For example, the 2nd example
above ( Nicragua) will have nulls in all the fields from field 6
through 53.

Following is the structure of the temp table
create table temptable1(
var1 varchar (10),
var2 varchar (10),
..
..
..
var53 varchar (10)
)

Regards,
VS

lalalulu24@.yahoo.com (TinTin) wrote in message news:<2d5425d1.0406160522.73ecb03@.posting.google.com>...
> Also:
> 53 values is the worse case scenario. Total number of variables could
> be 3 to 53. Script needs to check how many total variables there are
> and then likewise take action.
> "John Bell" <jbellnewsposts@.hotmail.com> wrote in message news:<VbLzc.1167$hb6.9819346@.news-text.cableinet.net>...
> > Hi
> > You will probably run into scope problems with this approach.
> > There seems to be a design issue here, but without knowing more about the
> > table strucures and what you are actually trying to do it is hard to suggest
> > a better solution other than hard coding each one or (as per your previous
> > post) look at using a temporary tables.
> > John
> > "TinTin" <lalalulu24@.yahoo.com> wrote in message
> > news:2d5425d1.0406151243.3bf0165a@.posting.google.c om...
> > > Hello,
> > > > How do I concatinate a variable. Here's the scenarios:
> > > > declare @.var1 varchar(20)
> > > declare @.var2 varchar(20)
> > > declare @.var3 varchar(20)
> > > declare @.var4 varchar(20)
> > > .
> > > .
> > > declare @.var32 varchar(20)
> > > > set @.var1 = 'Something 1'
> > > set @.var2 = 'Something 2'
> > > ...
> > > set @.var32 = 'Something 3'
> > > > /* I have to store the values of these individual variables. I wish to
> > > have a "While" routine which iterates through the above variables. I
> > > wish to have the variable name concatinated as that I do not have to
> > > write numerous lines of code setting up individual 32 variables. How
> > > could I use the '+' operator to join 'var' + @.count . Where count is
> > > from 1 through 32. I am having some trouble with the syntax.*/
> > > > Regards,
> > > VS|||It seems that the purpose of your stored procedure is to transform the
spreadsheet data into a form that you can use, presumably in a table. It is
possible to do this kind of transformation in SQL, it just isn't pretty!
Here
goes.

First, assume you have your sample data loaded into your temp table. I've
added a row number to help us later. You would obviously do this bit in DTS:

CREATE TABLE TempTable1 (rowno INTEGER IDENTITY PRIMARY KEY, col1
VARCHAR(20) NULL, col2 VARCHAR(20) NULL, col3 VARCHAR(20) NULL, col4
VARCHAR(20) NULL, col5 VARCHAR(20) NULL, col6 VARCHAR(20) NULL, col7
VARCHAR(20) NULL, col8 VARCHAR(20) NULL)

INSERT INTO TempTable1 (col1,col2) VALUES ('Country','Nigeria')
INSERT INTO TempTable1 (col1,col2) VALUES ('Region','African Continent')
INSERT INTO TempTable1 (col1,col2,col3,col4,col5,col6,col7,col8)
VALUES ('Gender','Male','Male','Male','Male','Male','Fema le','Female')
INSERT INTO TempTable1 (col1,col2,col3,col4,col5,col6,col7,col8)
VALUES ('Age Group','0-10','10-20','20-30','40-50','50-60','0-10','10-20')
INSERT INTO TempTable1 (col1,col2,col3,col4,col5,col6,col7,col8)
VALUES ('Total','200','323','111','3232','333','555','333 ')
INSERT INTO TempTable1 (col1,col2) VALUES ('Country','Nicaragua')
INSERT INTO TempTable1 (col1,col2) VALUES ('Region','African Continent')
INSERT INTO TempTable1 (col1,col2,col3,col4,col5,col6,col7)
VALUES ('Gender','Male','Male','Male','Female','Female',' Female')
INSERT INTO TempTable1 (col1,col2,col3,col4,col5,col6,col7)
VALUES ('Age Group','0-4','15-20','20-30','0-4','15-20','20-30')
INSERT INTO TempTable1 (col1,col2,col3,col4,col5,col6,col7)
VALUES ('Total','200','323','111','3232','112','441')

You haven't told us what the target structure is that you want to put the
data into. Based on your sample I'll assume it looks something like this:

CREATE TABLE SomeStats (country VARCHAR(20) NOT NULL /* REFERENCES Countries
(country) */, min_age INTEGER NOT NULL, max_age INTEGER NOT NULL, CHECK
(min_age>=0 AND max_age>min_age AND max_age<=120), gender CHAR(1) NOT NULL
CHECK (gender IN ('M','F')), stat INTEGER NOT NULL, PRIMARY KEY
(country,gender,min_age))

In reality you would probably want to use codes rather than country names.
The Continent name obviously belongs in the Countries table rather than here
so I've left it out.

Create a view:

CREATE VIEW TransformStats
AS
SELECT rowno, 1 AS col, col1 AS stat
FROM TempTable1
UNION ALL
SELECT rowno, 2 AS col, col2
FROM TempTable1
UNION ALL
SELECT rowno, 3 AS col, col3
FROM TempTable1
UNION ALL
SELECT rowno, 4 AS col, col4
FROM TempTable1
UNION ALL
SELECT rowno, 5 AS col, col5
FROM TempTable1
UNION ALL
SELECT rowno, 6 AS col, col6
FROM TempTable1
UNION ALL
SELECT rowno, 7 AS col, col7
FROM TempTable1
UNION ALL
SELECT rowno, 8 AS col, col8
FROM TempTable1

Finally, insert your data:

INSERT INTO SomeStats (country, min_age, max_age, gender, stat)
SELECT country,
LEFT(age,CHARINDEX('-',age)-1),
SUBSTRING(age,CHARINDEX('-',age)+1,20),
gender, stat
FROM
(SELECT
(SELECT stat
FROM TransformStats
WHERE rowno=
(SELECT MAX(rowno)
FROM TransformStats
WHERE col = 1
AND stat = 'Country'
AND rowno <= T.rowno)
AND col=2) AS country,
(SELECT stat
FROM TransformStats
WHERE rowno=
(SELECT MAX(rowno)
FROM TransformStats
WHERE col = 1
AND stat = 'Age Group'
AND rowno <= T.rowno)
AND col=T.col) AS age,
(SELECT LEFT(stat,1)
FROM TransformStats
WHERE rowno=
(SELECT MAX(rowno)
FROM TransformStats
WHERE col = 1
AND stat = 'Gender'
AND rowno <= T.rowno)
AND col=T.col) AS gender,
stat
FROM
TransformStats AS T
WHERE ISNUMERIC(stat)=1) AS T

This will of course fail if your spreadsheets aren't in a fairly regular,
predictable format. This is an unavoidable problem with spreadsheet data and
there isn't an easy solution except to find a reliable, structured data
source. Your data looks somewhat suspect anyway. Last time I checked my
atlas Nicragua [sic] wasn't in Africa :)

Hope this helps.

--
David Portas
SQL Server MVP
--

Friday, February 10, 2012

Concatenating string variables doesn't appear to work properly

When executing the following statements:
declare @.x char(10), @.y char(10)
set @.x = 'abc'
set @.y = @.x + 'def'
select @.x
select @.y
the results are:
abc
abc
I expect @.y should be equal to 'abcdef'. If I change the var types to
int for example, then @.y is summed correctly. Can anyone tell me why,
or what I'm doing wrong? Thanks.
DanOn Feb 21, 1:42 pm, dan.for...@.matrikon.com wrote:
> When executing the following statements:
> declare @.x char(10), @.y char(10)
> set @.x = 'abc'
> set @.y = @.x + 'def'
> select @.x
> select @.y
> the results are:
> abc
> abc
> I expect @.y should be equal to 'abcdef'. If I change the var types to
> int for example, then @.y is summed correctly. Can anyone tell me why,
> or what I'm doing wrong? Thanks.
> Dan
@.x is defined as a CHAR(10), and as we know, the CHAR datatype
includes trailing spaces. When you assign the value 'abc' to @.x, its
value is really 'abc '. When you then append 'def' to it, you
are actually getting 'abc def', but since @.y is also defined as
CHAR(10), it can only hold the first 10 characters, which are
'abc '. Use VARCHAR(10) instead.|||In addition to Tracy's precise comment, this might help explaining it
further.
select datalength(@.x), datalength(@.x+'def')
--
-oj
<dan.forest@.matrikon.com> wrote in message
news:1172086921.411352.88210@.v33g2000cwv.googlegroups.com...
> When executing the following statements:
> declare @.x char(10), @.y char(10)
> set @.x = 'abc'
> set @.y = @.x + 'def'
> select @.x
> select @.y
> the results are:
> abc
> abc
> I expect @.y should be equal to 'abcdef'. If I change the var types to
> int for example, then @.y is summed correctly. Can anyone tell me why,
> or what I'm doing wrong? Thanks.
> Dan
>|||On Feb 21, 12:49 pm, "Tracy McKibben" <tracy.mckib...@.gmail.com>
wrote:
> On Feb 21, 1:42 pm, dan.for...@.matrikon.com wrote:
>
>
> > When executing the following statements:
> > declare @.x char(10), @.y char(10)
> > set @.x = 'abc'
> > set @.y = @.x + 'def'
> > select @.x
> > select @.y
> > the results are:
> > abc
> > abc
> > I expect @.y should be equal to 'abcdef'. If I change the var types to
> > int for example, then @.y is summed correctly. Can anyone tell me why,
> > or what I'm doing wrong? Thanks.
> > Dan
> @.x is defined as a CHAR(10), and as we know, the CHAR datatype
> includes trailing spaces. When you assign the value 'abc' to @.x, its
> value is really 'abc '. When you then append 'def' to it, you
> are actually getting 'abc def', but since @.y is also defined as
> CHAR(10), it can only hold the first 10 characters, which are
> 'abc '. Use VARCHAR(10) instead.- Hide quoted text -
> - Show quoted text -
Thanks. I wasn't aware of the trailing spaces.
Dan|||On Feb 21, 2:36 pm, dan.for...@.matrikon.com wrote:
> Thanks. I wasn't aware of the trailing spaces.
> Dan
That's the "simplest" way to describe the difference between CHAR and
VARCHAR. CHAR is for fixed-length strings and always contains the
number of characters it's defined for, whereas VARCHAR (variable-CHAR)
is for variable length strings, and only contains what you
specifically put in it.

Concatenating string variables doesn't appear to work properly

When executing the following statements:
declare @.x char(10), @.y char(10)
set @.x = 'abc'
set @.y = @.x + 'def'
select @.x
select @.y
the results are:
abc
abc
I expect @.y should be equal to 'abcdef'. If I change the var types to
int for example, then @.y is summed correctly. Can anyone tell me why,
or what I'm doing wrong? Thanks.
DanOn Feb 21, 1:42 pm, dan.for...@.matrikon.com wrote:
> When executing the following statements:
> declare @.x char(10), @.y char(10)
> set @.x = 'abc'
> set @.y = @.x + 'def'
> select @.x
> select @.y
> the results are:
> abc
> abc
> I expect @.y should be equal to 'abcdef'. If I change the var types to
> int for example, then @.y is summed correctly. Can anyone tell me why,
> or what I'm doing wrong? Thanks.
> Dan
@.x is defined as a CHAR(10), and as we know, the CHAR datatype
includes trailing spaces. When you assign the value 'abc' to @.x, its
value is really 'abc '. When you then append 'def' to it, you
are actually getting 'abc def', but since @.y is also defined as
CHAR(10), it can only hold the first 10 characters, which are
'abc '. Use VARCHAR(10) instead.|||In addition to Tracy's precise comment, this might help explaining it
further.
select datalength(@.x), datalength(@.x+'def')
-oj
<dan.forest@.matrikon.com> wrote in message
news:1172086921.411352.88210@.v33g2000cwv.googlegroups.com...
> When executing the following statements:
> declare @.x char(10), @.y char(10)
> set @.x = 'abc'
> set @.y = @.x + 'def'
> select @.x
> select @.y
> the results are:
> abc
> abc
> I expect @.y should be equal to 'abcdef'. If I change the var types to
> int for example, then @.y is summed correctly. Can anyone tell me why,
> or what I'm doing wrong? Thanks.
> Dan
>|||On Feb 21, 12:49 pm, "Tracy McKibben" <tracy.mckib...@.gmail.com>
wrote:
> On Feb 21, 1:42 pm, dan.for...@.matrikon.com wrote:
>
>
>
>
>
>
>
>
> @.x is defined as a CHAR(10), and as we know, the CHAR datatype
> includes trailing spaces. When you assign the value 'abc' to @.x, its
> value is really 'abc '. When you then append 'def' to it, you
> are actually getting 'abc def', but since @.y is also defined as
> CHAR(10), it can only hold the first 10 characters, which are
> 'abc '. Use VARCHAR(10) instead.- Hide quoted text -
> - Show quoted text -
Thanks. I wasn't aware of the trailing spaces.
Dan|||On Feb 21, 2:36 pm, dan.for...@.matrikon.com wrote:
> Thanks. I wasn't aware of the trailing spaces.
> Dan
That's the "simplest" way to describe the difference between CHAR and
VARCHAR. CHAR is for fixed-length strings and always contains the
number of characters it's defined for, whereas VARCHAR (variable-CHAR)
is for variable length strings, and only contains what you
specifically put in it.

Concatenating string variables doesn't appear to work properly

When executing the following statements:
declare @.x char(10), @.y char(10)
set @.x = 'abc'
set @.y = @.x + 'def'
select @.x
select @.y
the results are:
abc
abc
I expect @.y should be equal to 'abcdef'. If I change the var types to
int for example, then @.y is summed correctly. Can anyone tell me why,
or what I'm doing wrong? Thanks.
Dan
On Feb 21, 1:42 pm, dan.for...@.matrikon.com wrote:
> When executing the following statements:
> declare @.x char(10), @.y char(10)
> set @.x = 'abc'
> set @.y = @.x + 'def'
> select @.x
> select @.y
> the results are:
> abc
> abc
> I expect @.y should be equal to 'abcdef'. If I change the var types to
> int for example, then @.y is summed correctly. Can anyone tell me why,
> or what I'm doing wrong? Thanks.
> Dan
@.x is defined as a CHAR(10), and as we know, the CHAR datatype
includes trailing spaces. When you assign the value 'abc' to @.x, its
value is really 'abc '. When you then append 'def' to it, you
are actually getting 'abc def', but since @.y is also defined as
CHAR(10), it can only hold the first 10 characters, which are
'abc '. Use VARCHAR(10) instead.
|||In addition to Tracy's precise comment, this might help explaining it
further.
select datalength(@.x), datalength(@.x+'def')
-oj
<dan.forest@.matrikon.com> wrote in message
news:1172086921.411352.88210@.v33g2000cwv.googlegro ups.com...
> When executing the following statements:
> declare @.x char(10), @.y char(10)
> set @.x = 'abc'
> set @.y = @.x + 'def'
> select @.x
> select @.y
> the results are:
> abc
> abc
> I expect @.y should be equal to 'abcdef'. If I change the var types to
> int for example, then @.y is summed correctly. Can anyone tell me why,
> or what I'm doing wrong? Thanks.
> Dan
>
|||On Feb 21, 12:49 pm, "Tracy McKibben" <tracy.mckib...@.gmail.com>
wrote:
> On Feb 21, 1:42 pm, dan.for...@.matrikon.com wrote:
>
>
>
>
>
> @.x is defined as a CHAR(10), and as we know, the CHAR datatype
> includes trailing spaces. When you assign the value 'abc' to @.x, its
> value is really 'abc '. When you then append 'def' to it, you
> are actually getting 'abc def', but since @.y is also defined as
> CHAR(10), it can only hold the first 10 characters, which are
> 'abc '. Use VARCHAR(10) instead.- Hide quoted text -
> - Show quoted text -
Thanks. I wasn't aware of the trailing spaces.
Dan
|||On Feb 21, 2:36 pm, dan.for...@.matrikon.com wrote:
> Thanks. I wasn't aware of the trailing spaces.
> Dan
That's the "simplest" way to describe the difference between CHAR and
VARCHAR. CHAR is for fixed-length strings and always contains the
number of characters it's defined for, whereas VARCHAR (variable-CHAR)
is for variable length strings, and only contains what you
specifically put in it.

Concatenating a fully qualified name

In the code below, the DatabaseName and table_id are variables. The table_id
is OK with the @.table_id. But, how do I make DatabaseName equal to @.db so
that I can pass it to the parameter @.database. In other words, how do I
concatenate so that it will be something like this @.db.dbo.tblName:
CREATE PROCEDURE sampleProcedure
(
@.database varchar (100),
@.table_id uniqueidentifier
)
AS
SET NOCOUNT ON
DECLARE @.db varchar (100)
SELECT @.db = @.database
INSERT INTO DatabaseName.dbo.tblName
SELECT * FROM tblName where table_id=@.table_idHello,
You need to use Dynamic SQL to do this.After that execute the Dynamic SQL
using EXEC or SP_ExecuteSQL. Take a look int the article.
http://www.sommarskog.se/dynamic_sql.html
Thanks
Hari
"morphius" <morphius@.discussions.microsoft.com> wrote in message
news:92783839-67A2-4880-938D-699519E3A9C0@.microsoft.com...
> In the code below, the DatabaseName and table_id are variables. The
> table_id
> is OK with the @.table_id. But, how do I make DatabaseName equal to @.db so
> that I can pass it to the parameter @.database. In other words, how do I
> concatenate so that it will be something like this @.db.dbo.tblName:
> CREATE PROCEDURE sampleProcedure
> (
> @.database varchar (100),
> @.table_id uniqueidentifier
> )
> AS
> SET NOCOUNT ON
> DECLARE @.db varchar (100)
> SELECT @.db = @.database
> INSERT INTO DatabaseName.dbo.tblName
> SELECT * FROM tblName where table_id=@.table_id

Concatenating a fully qualified name

In the code below, the DatabaseName and table_id are variables. The table_id
is OK with the @.table_id. But, how do I make DatabaseName equal to @.db so
that I can pass it to the parameter @.database. In other words, how do I
concatenate so that it will be something like this @.db.dbo.tblName:
CREATE PROCEDURE sampleProcedure
(
@.database varchar (100),
@.table_id uniqueidentifier
)
AS
SET NOCOUNT ON
DECLARE @.db varchar (100)
SELECT @.db = @.database
INSERT INTO DatabaseName.dbo.tblName
SELECT * FROM tblName where table_id=@.table_idHello,
You need to use Dynamic SQL to do this.After that execute the Dynamic SQL
using EXEC or SP_ExecuteSQL. Take a look int the article.
http://www.sommarskog.se/dynamic_sql.html
Thanks
Hari
"morphius" <morphius@.discussions.microsoft.com> wrote in message
news:92783839-67A2-4880-938D-699519E3A9C0@.microsoft.com...
> In the code below, the DatabaseName and table_id are variables. The
> table_id
> is OK with the @.table_id. But, how do I make DatabaseName equal to @.db so
> that I can pass it to the parameter @.database. In other words, how do I
> concatenate so that it will be something like this @.db.dbo.tblName:
> CREATE PROCEDURE sampleProcedure
> (
> @.database varchar (100),
> @.table_id uniqueidentifier
> )
> AS
> SET NOCOUNT ON
> DECLARE @.db varchar (100)
> SELECT @.db = @.database
> INSERT INTO DatabaseName.dbo.tblName
> SELECT * FROM tblName where table_id=@.table_id

Concatenating a fully qualified name

In the code below, the DatabaseName and table_id are variables. The table_id
is OK with the @.table_id. But, how do I make DatabaseName equal to @.db so
that I can pass it to the parameter @.database. In other words, how do I
concatenate so that it will be something like this @.db.dbo.tblName:
CREATE PROCEDURE sampleProcedure
(
@.database varchar (100),
@.table_id uniqueidentifier
)
AS
SET NOCOUNT ON
DECLARE @.db varchar (100)
SELECT @.db = @.database
INSERT INTO DatabaseName.dbo.tblName
SELECT * FROM tblName where table_id=@.table_id
Hello,
You need to use Dynamic SQL to do this.After that execute the Dynamic SQL
using EXEC or SP_ExecuteSQL. Take a look int the article.
http://www.sommarskog.se/dynamic_sql.html
Thanks
Hari
"morphius" <morphius@.discussions.microsoft.com> wrote in message
news:92783839-67A2-4880-938D-699519E3A9C0@.microsoft.com...
> In the code below, the DatabaseName and table_id are variables. The
> table_id
> is OK with the @.table_id. But, how do I make DatabaseName equal to @.db so
> that I can pass it to the parameter @.database. In other words, how do I
> concatenate so that it will be something like this @.db.dbo.tblName:
> CREATE PROCEDURE sampleProcedure
> (
> @.database varchar (100),
> @.table_id uniqueidentifier
> )
> AS
> SET NOCOUNT ON
> DECLARE @.db varchar (100)
> SELECT @.db = @.database
> INSERT INTO DatabaseName.dbo.tblName
> SELECT * FROM tblName where table_id=@.table_id