Select Several Values Into A Single Variable

May 11, 2006

Can somebody please tell me whether the following syntax is supported
or whether it's a "feature" that will someday stop working. It works in
both SQL Server 2000 and 2005 at the moment.

declare @var varchar(1000)
set @var = ''
select @var = @var + colx from some_table where col1 = some_value

colx is a varchar or at least is cast to one as part of the select
statement. If the where clause would normally return more than one row,
all returned values for colx are concatenated into @var.
I've not seen this syntax before but that doesn't make it wrong ;-)

Malc.

View 8 Replies


ADVERTISEMENT

HOw Can Use Single Quotes With Variable In Select Caluse

Aug 18, 2007

define @strName as varchar(50) NULL

set @strName=(SELECT strname from Table)

SELECT '+ @strName +' from Table

It does not work

View 1 Replies View Related

Select Comma Separated Values From Single Column

May 27, 2008

Hi,

I have a table -- Table1.
It has two columns -- Name and Alpha.
Alpha has comma separated values like -- (A,B,C,D,E,F), (E,F), (D,E,F), (F), (A,B,C).

I need to pick the values of column -- Name , where in values of Alpha is less than or equal to 'D'.

I tried <=, but got only values less than 'D', but was not able to get equal to 'D'.

Any suggestions??

View 4 Replies View Related

Transact SQL :: SELECT Unique Values In Single Column?

Jun 8, 2015

I have the following two tables...

tblServer
-serverID
-serverName
-serverLocation
tblSite
-siteID
-serverID
-siteName
-siteIpAddress

I need to write a select query that gets the values of all columns but only returns unique sites because some sites are load balanced across several servers and where this is the case I don't want the site to appear multiple times in the list.

View 4 Replies View Related

SQL Server 2012 :: How To Replace Multiple Values In Single Select Statement

Aug 18, 2015

how we can replace the multiple values in a single select statement? I have to build the output based on values stored in a table. Please see below the sample input and expected output.

DECLARE @V1 NVARCHAR(100)
SELECT @V1 = 'FirstName: @FN, LastName: @LN, Add1: @A1, Add2: @A2 '
DECLARE @T1 TABLE
(FN VARCHAR(100), LN VARCHAR(100), A1 VARCHAR(100), A2 VARCHAR(100))

[code]....

View 7 Replies View Related

Transact SQL :: Converting From Multiple Rows With Single Values To Single Rows With Multiple Values

May 10, 2015

Here is some data that will explain what I want to do:

Input Data:
Part ColorCode
A100 123
A100 456
A100 789
B100 456
C100 123
C100 456

Output Data:
Part ColorCode
A100 123;456;789
B100 456
C100 123;456

View 4 Replies View Related

Transact SQL :: Insert Values From Variable Into Table Variable

Nov 4, 2015

CREATE TABLE #T(branchnumber VARCHAR(4000))

insert into #t(branchnumber) values (005)
insert into #t(branchnumber) values (090)
insert into #t(branchnumber) values (115)
insert into #t(branchnumber) values (210)
insert into #t(branchnumber) values (216)

[code]....

I have a parameter which should take multiple values into it and pass that to the code that i use. For, this i created a parameter and temporarily for testing i am passing some values into it.Using a dynamic SQL i am converting multiple values into multiple records as rows into another variable (called @QUERY). My question is, how to insert the values from variable into a table (table variable or temp table or CTE).OR Is there any way to parse the multiple values into a table. like if we pass multiple values into a parameter. those should go into a table as rows.

View 6 Replies View Related

How To Enclose Variable In Single Quotes In SP

Oct 9, 2015

Here is what I would like to execute

SELECT * FROM sale
WHERE id =1 AND caldate >='10/1/2015' AND caldate <='10/31/2015'
and I don't know how to write this in SP
CREATE PROCEDURE [dbo].[sale]
@id int,

[Code] ...

Is this a correct way to enclose a variable in single quotes?

View 6 Replies View Related

Variable Insert To SQL Server Insert Satement Setting Values For The @variable INSIDE Sql

Apr 29, 2007

ok, I am on Day 2 of being brain dead.I have a database with a table with 2 varchar(25) columns I have a btton click event that gets the value of the userName,  and a text box.I NEED to insert a new row in a sql database, with the 2 variables.Ive used a sqldatasource object, and tried to midify the insert parameters, tried to set it at the button click event, and NOTHING is working. Anyone have a good source for sql 101/ASP.Net/Braindead where I can find this out, or better yet, give me an example.  this is what I got <%@ Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">     protected void runit_Click(object sender, EventArgs e)    {       //SqlDataSource ID = "InsertExtraInfo".Insert();      //SqlDataSource1.Insert();    }      protected void Button1_Click1(object sender, EventArgs e)    {        SqlDataSource newsql;                newsql.InsertParameters.Add("@name", "Dan");        newsql.InsertParameters.Add("@color", "rose");        String t_c = "purple";        string tempname = Page.User.Identity.Name;        Label1.Text = tempname;        Label2.Text = t_c;        newsql.Insert();    }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>mini update</title></head><body>    <form id="form1" runat="server">        &nbsp;name<asp:TextBox ID="name" runat="server" OnTextChanged="TextBox2_TextChanged"></asp:TextBox><br />        color        <asp:TextBox ID="color" runat="server"></asp:TextBox><br />        <br />        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Button" />        &nbsp;<br />        set lable =&gt;<asp:Label ID="Label1" runat="server" Text="Label" Width="135px" Visible="False"></asp:Label><br />        Lable 2 =&gt;        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />        Usernmae=&gt;<asp:LoginName ID="LoginName1" runat="server" />        <br />        <br />        <br />        <br />        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"            ConnectionString="<%$ ConnectionStrings:newstring %>" DeleteCommand="DELETE FROM [favcolor] WHERE [name] = @original_name AND [color] = @original_color"            InsertCommand="INSERT INTO [favcolor] ([name], [color]) VALUES (@name, @color)"            OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [name], [color] FROM [favcolor]"            UpdateCommand="UPDATE [favcolor] SET [color] = @color WHERE [name] = @original_name AND [color] = @original_color">            <DeleteParameters>                <asp:Parameter Name="original_name" Type="String" />                <asp:Parameter Name="original_color" Type="String" />            </DeleteParameters>            <UpdateParameters>                <asp:Parameter Name="color" Type="String" />                <asp:Parameter Name="original_name" Type="String" />                <asp:Parameter Name="original_color" Type="String" />            </UpdateParameters>            <InsertParameters>        <asp:InsertParameter("@name", "Dan", Type="String" />        <asp:InsertParameter("@color", "rose") Type="String"/>                                       </InsertParameters>        </asp:SqlDataSource>        &nbsp;        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"            AutoGenerateColumns="False" DataKeyNames="name" DataSourceID="SqlDataSource1">            <Columns>                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />                                <asp:BoundField DataField="color" HeaderText="color" SortExpression="color" />                <asp:BoundField DataField="name" HeaderText="name" ReadOnly="True" SortExpression="name" />            </Columns>        </asp:GridView>           </form></body></html>  

View 1 Replies View Related

Putting Zero At Front Of A Single Digit Variable?

Sep 28, 2014

I am retrieving the current month and setting a variable accordingly.

Code:
DECLARE @currMonthNum INT
SET @currMonthNum = DATEPART(MM, GETDATE())

My challenge is that at a later point I want to use the @currMonthNum value to 'build' a date in the style yyyymmdd and the variable is only one digit for the months January to September (e.g.: 1 to 9). For the months January to September I need to pad the variable with an extra zero (e.g.: 01 to 09).

Here is my attempt to do this...!

Code:
IF @currMonthNum IN (1, 2, 3, 4, 5, 6, 7, 8, 9)
SET @currMonthNum = '0' + CAST(@currMonthNum AS nvarchar)

Unfortunately this does not give the desired result of two digits, however ironically if I add a + '0' to the end I get 10 to 90! It is like the 0 at the front is simply being ignored.

I have also tried setting the @currMonthNum variable to an nvarchar type before performing the character addition as well attempting to use the CONCAT command (however I don't think that CONCAT can be used when setting a variable).

how to display a zero in front of the months that require it?

View 4 Replies View Related

UPDATE A Variable To Different Categories By A Single Step?

Jul 23, 2005

Hello,I am trying to update variable 'Type' (which is a pre-defined variablewithout any value in it). Is there a way to combine Step1 to Step3 intoone single Update? I tried the query at the bottom but it didn't work.Thanks a lot!--STEP1:Update TABLE1set type = casewhen name like '%Airline%' then 'Airlines'else 'Others'end--STEP2:update TABLE1set type = casewhen name like '%Brokerage%' then 'Brokerage'else 'Others'endwhere type = 'Others'--STEP3:update TABLE1set type = casewhen name like '%card%' then 'Credit Card'else 'Others'endwhere type = 'Others'--Failed query:Update TABLE1set type = casewhen name like '%Airline%' then 'Airlines'else when name like '%Brokerage%' then 'Brokerage'else when name like '%card%' then 'Credit Card'else 'Others'end

View 6 Replies View Related

ADD A COLUMN AND POPULATE IT WITH A SINGLE VALUE FROM A USER VARIABLE

Sep 29, 2006

Hi !

I have one Excel source with ... say 2 columns, I have an SQL Server destination with 3 columns.

I want the third column to be populated with a single value stored in a User::Variable.

Can someone help !

Jacques...

View 3 Replies View Related

Read Single Piece Of Data From SqlDataSource To A Variable?

Jan 17, 2006

First I want to say thanks to the folks how have helped me over the past week or two.
I'm missing a crucial piece of insight. How do I read a single piece of data from a SqlDataSource which only hold one row of data into a declared variable?
string zUserName = SqlDataSource.(get the value in the row that is labeled UserName)
It really doesn't matter to me whether it is an SqlDataSource or some other data container that hold the data I've selected. My goal is to be able to read some data from some predefined datasource into a declared variable.
If I am approaching this problem in the wrong way any advice or article links you could give me would be grealy appreciate.
Thanks, Bill

View 1 Replies View Related

T-SQL (SS2K8) :: Inserting Multiple Records From A Single Variable?

Apr 24, 2014

I have two tables. Table 1 has column "job", table 2 has column "job" and column "item". In table table 2 there are multiple "items" for each "job"

I would like to insert all of the "items" into table 1, based on a join table1.job = table2.job

View 7 Replies View Related

T-SQL (SS2K8) :: Error Single Quote Stored In Variable

Sep 2, 2014

I'm trying to create a Character string so that I can execute dynamic SQL.

The date is going to change.

DECLARE @Select VARCHAR (50)
DECLARE @SQLQuery VARCHAR (500)
DECLARE @PreSelect CHAR (1)
DECLARE @CurrentDate Date
SET @SQLQuery = 'SELECT CAST(CAE_RDB_ENTRY_DATE as Date), *
FROM OPENQUERY(LS_RDB_DWH,'
SET @PreSelect = '''
SELECT @Preselect AS PreSelect

If I try this statement which what I really want. I would like to include the Quote with the Select.:

SET @Select = ''SELECT * FROM RDB_DWH_ASSOCIATE_ENTITY WHERE CAE_RDB_ENTRY_DATE >''

I get the following error:

Invalid object name 'RDB_DWH_ASSOCIATE_ENTITY'.

View 9 Replies View Related

Multiple Values For Single Row

Mar 19, 2007

hi iam totally new to databases , as a project i have to design a database of users...they have to register first like any site..so i used stored procs and made entries to database using insert command...its working for now..now every user will search and add other users in the database..so every user will have a contact list...i have no idea how to implement this...so far i created a table 'UserAccount' with column names as UserName as varchar(50)Password as varchar(50)EmailID as varchar(100)DateOfJoining as datetimeUserID as int ---> this is unique for user..i enabled automatic increment..and this is primary key..so now every user must have a list of other userid's.. as contact list..Any help any ideas will be great since i have no clue how to put multiple values for each row..i didnt even know how to search for this problems solution..iam sorry if this posted somewhere else..THANK YOU !if it helps..iam using sql server express edition..and iam accessing using asp.net/C#

View 1 Replies View Related

Cannot Set A Variable From A Select Statement That Contains A Variable??? Help Please

Oct 4, 2006

I am trying to set a vaiable from a select statement

DECLARE @VALUE_KEEP NVARCHAR(120),

@COLUMN_NAME NVARCHAR(120)



SET @COLUMN_NAME = (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'CONTACTS' AND COLUMN_NAME = 'FIRSTNAME')



SET @VALUE_KEEP = (SELECT @COLUMN_NAME FROM CONTACTS WHERE CONTACT_ID = 3)



PRINT @VALUE_KEEP

PRINT @COLUMN_NAME



RESULTS

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

FirstName <-----------@VALUE_KEEP

FirstName <-----------@COLUMN_NAME



SELECT @COLUMN_NAME FROM CONTACTS returns: FirstName

SELECT FirstName from Contacts returns: Brent



How do I make this select statement work using the @COLUMN_NAME variable?

Any help greatly appreciated!

View 2 Replies View Related

Integration Services :: Single-row Result From Querying Binding With Variable

Jul 20, 2007

I set up a connection to mysql using ADO.NET's ODBC Data Provider. And I'm running a simple query to return one table's maximum ID(int32 unsigned).But when I bind the result to a variable and excute task. It gives out error message: "An error occurred while assigning a value to variable "MaxAuditLogID": "Result binding by name "MaxID" is not supported for this connection type. " I tried to change the type of variable around but with no luck.  

View 5 Replies View Related

How To Add All The Values In A Single Column In A Table?

Oct 6, 2005

numbers     2     4     2Above is an example of my table with a single column. My problem is how to add all the numbers in that column to make it 8? The rows are also dynamic. Your help is highly appreciated.

View 4 Replies View Related

Store Multiple Values In A Single Value

Nov 6, 2005

was hoping someone couild provide some insight into a problem I'm trying to solve.

I have a table called SEARCHCRITERIA. It consists of a USERID column and a CRITERIA column. Users will be able to search for other users based on a set of criteria. There are 5 total criteria a user can choose. They can choose as few as none or all five. I'd like to store the criteria chosen as a single number in the SEARCHCRITERIA table. Then use a function to parse out the criteria. For example:

CRITERIAID CRITERIA CRITERIAVALUE
1 AGE 2
2 SEX 4
3 GRADE 8
4 LOCALE 16
5 REGION 32

A user performs a search based on AGE, SEX, and LOCALE. I would then store the value 22 (the sum of 2, 4, and 16) in the SEARCH table. I would then need a function to pull out the three individual values.

Has anyone done anything like this before?

If so, any help would be appreciated!

Thanks in advance!

View 1 Replies View Related

Rowset Values In A Single String

Apr 8, 2004

I am not close to an sql server today and this question was posed to me. can someone hook me up?

" I want to query a column of values and place them into a single string seperated by commas" (as a function)

Table a
123
456
789
321
654
987


output
123,456,789,321,654,987

thanks in advance

View 14 Replies View Related

Splitting Up Of Values In Single Column

May 21, 2008

Hi,

I have a table that has multiple postal codes in one of the columns. Those have to be split up one per line and stored in another table. The zip codes are comma seperated. Is there a function that can do this...?

Example data in ZipCodeTable. (Name and ZipCode are 2 columns in a table)

NameZipCode
Area119930,19970,19971,19944
Area219934,19938,19901,19903,19904
Area319994,19838

output Table should be:

NameZipCode
Area119930
Area119970
Area119971
Area119944
Area219934
Area219938
Area219901
Area219903
Area219904
Area319994
Area319838

Any thoughts on this would be of much help !!..

Thanks

View 7 Replies View Related

Returning Values From 2 Queries To A Single Row?

Sep 30, 2014

I have a query set that returns values as part of a data set, I need a new one to return values from two queries to a single row.

select '1' as thekey, 'Total Picks' as Tot,sum(prod_qty) as picks from exceed.aseld, exceed.csymh
where luis_id in ('I','E')
and aseld.whse_id = 1
and (
(aseld.batch_id between goal_beg_batch and goal_end_batch
and monitor_group = 'YK')

[code]....

is it possible to get the numbers from keys 1 & 2 on the same row in a new query?

Or if it is easier a query that with give me (completed picks/total picks) = a decimal I can feed to the display as a percentage.

View 3 Replies View Related

Multiple Values Into Single Cell

May 18, 2007

Taking the Northwind database as an example,I have an order table: 'Orders'a order details table: 'Order Details'and a products table: 'Products'For reasons best ignored, I want to produce a query which has columns:Orders.OrderID, Productswhich has results like:10248, 'Queso Cabrales, Singaporean Hokkien Fried Mee, Mozzarella diGiovanni'10249, 'Tofu, Manjimup Dried Apples'________so for those who don't really know what I'm on about and haven't gotaccess to northwind, I want the second cell to contain the returnedcolumn of a second query (but in text format)could anyone suggest a way this could be done? am I entering the landof cursors?Many thanks,Neil

View 4 Replies View Related

Integration Services :: How To Get All Row Values In Single Row

Aug 17, 2015

Tried with Pivot but I'm not getting expected results for the requirement.

SUB             Tests               Marks
----------------------------------------
Maths          Test1              50
maths          test2              60
maths          test3              50
maths          test4              80
English         test1             35
English        test2              60
physics        test4              80

Results need to be shown as below.

sub          test1      test2  test3  test4   
--------------------------------------------------
maths     50        60         50         80
English    35        60        null        null
physics   null       null       null        80

View 3 Replies View Related

Select Values From One Table Based Upon Values In Another...

May 19, 2006

How do I:Select f1, f2, f3, from tb1 where f1=Select f1 from tb2 where f1='condition'?

View 3 Replies View Related

SQL Server 2012 :: Assigning Multiple Rows To A Single Variable Parameter

Nov 27, 2014

The following works in query if I specify one student (PlanDetailUID) when running query. If I try to specify multiple students (PlanDetailUID) when running query, I get variable cannot take multiple entries. I assume I would need to replace (variables) in PART 2 with (case statements / using select everywhere) to get around the issue or is there a better way ?

CREATE TABLE #AWP (
[TransDate] [datetime] NULL,
[Description] [varchar](1000) NULL,
[Amount] [float] NULL,
[TotalDueNow] [float] NULL,

[code]....

View 4 Replies View Related

Passing Multiple Values To A Single Parameters

Dec 28, 2007

I have a SQL query that goes like this
"select * from Product where ProductID in (1,2,3)"
How can i create a stored procedure where a single input parameter can take multiple values?
Can anyone help me with this?

View 4 Replies View Related

Multiple Values For Single Column In Where Clause

Jun 25, 2004

how does one specify multiple values for a single column in a where clause?

example:

SELECT fname, lname
FROM tblContacts
WHERE (state = 'MI','CA','AZ','TN','NJ')


if my memory serves me there is an IN() value list operator but I can't remember the syntax :confused:

View 2 Replies View Related

How To Create A Matrix Of Values From A Single Table

Aug 28, 2013

I'm a real novice user and I we use SQL Server. I have a table called TableLog that has the 4 columns. The first column is repeated x number of times for each value in the second column. I'd like to see this information put into a matrix where I could tell if there are any missing intersections. In addition, I need to insert a WHERE clause that says "BETWEEN 20090000 AND 20100000" for the first and second columns.

Example data in the table:

ID1 ID2 MRSSI
100 200 63
100 300 63
200 100 63
200 300 63
300 100 63

Desired matrix: P = Pass and F = Fail

100 200 300
100 n/a P P
200 P n/a P
300 P F P

From the example data, there's no intersection for 300 and 200 so a F is displayed.

View 3 Replies View Related

Find Values From String In A Single Cell

Jan 10, 2014

I have a program which feeds back information to a table within my database. The annoying thing is that only 1 of the table cells has all of the information I need so essentially I have a large string of data I need to retrieve values from.I retrieve my cell with a simple select details from alerts where ID = (alert number).The results I have are as follows:

[INFO] Dashboard Output Information:
[LastUpdated]
Time=09:59
[LastProcessed]
LastProcessed=*2911
Updated=09:59
[LastReceived]
LastReceived=#10
Updated=09:59

As you can see I have a list (its larger but this is a sample), the only thing I need are the values for each section so for last processed i want the 2911 so I can use it on my dashboard and the last received I want the 10 for that section.i have read about using substrings but am really not sure where to start and how I'd go about getting these values to then use elsewhere?

View 3 Replies View Related

Concatenate Values From Same Column But Different Record In Single Row

Mar 26, 2008

Hi, I have a difficult case that I need to solve. I will try to be the very clear explaining my problem:


I have a sql query which brings me many records.
This records have a column in common which have the same value (COL1)

There is a second column (COL2) which has different values bewteen these records.
I need to concatenate values from the second column in records with same value in COL1. And I need only one record of the ones that have the same values. If two records have the same COL1 value, only one row should be in my result.

Let me give you an example:
COL1 COL2
RECORD1 1-A HHH
RECORD2 1-A GGG
RECORD3 1-B LLL
RECORD4 1-B MMM
RECORD4 1-B OOO
RECORD5 1-C NNN

Me result should be:


COL1 COL2
RECORD 1-A HHHGGG
RECORD 1-B LLLMMMOOO
RECORD 1-C NNN

It is clear what I need? I dont know if I can solve it through sql or any function inside SSIS.
Thanks for any help you can give me.

View 5 Replies View Related

In SSIS Execute SQL Task, Single-row Result From Querying Mysql Binding With A Variable

Jul 20, 2007

I set up a connection to mysql using ADO.NET's ODBC Data Provider. And I'm running a simple query to return one table's maximum ID(int32 unsigned). There is no problem to achieve that.



But when I bind the result to a variable and excute task. It gives out error message: "An error occurred while assigning a value to variable "MaxAuditLogID": "Result binding by name "MaxID" is not supported for this connection type. "



I tried to change the type of variable around but with no luck.



Could anyone help with this issue? Thanks!

View 6 Replies View Related







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