SQL Server 2008 column select - sql

In SQL Server, if I got a table with like 20 columns and I want 18 of them, can I say something like * minus columnname1, columnname2, course right now I write them all.
But if you could it would be much easier.

Little hint to replace the asterisk with column names in SQL Management Studio in no time without any fancy plugin:
Select your written query (no matter how many joins, etc.)
Right click and select "Design Query in Editor..."
Simply click "Ok"
The asterisk should have been expanded to column names now :)
Ofc it's possible to select/deselect any column in the query editor..
Hth

It is not possible. However if you are using SQL Server Management Studio 2008 / 2005 you can right click on the table and select the "Script Table as > SELECT To" menu option. This will save you typing the column names, or purchase Red-Gate's SQL Prompt

Out of the box - no, it's not possible. You have to spell out all the columns you want explicitly.
With SQL Server Management Studio 2008, there is intellisense which can help you select columns from a table - so that's certainly one step to help ease the pain.
Add-in tools like SQL Prompt offer more help - in SQL Prompt, you can type
SELECT *
FROM dbo.YourTable
and if you have the cursor just after the asterisk symbol (*), you can press <TAB> and expand the asterisk into the list of all columns for that table (and then remove the two you don't want) - or you can popup a window and pick those columns you really want.
Very handy, very useful, very much speeding up development - but it's not a free tool.....

You can use select TOP (18) * from givenTable is you want 18 rows.
There is no such method for columns. In fact column names are stored in master db and you can extract them and consruct query looking like what you are asking for BUT it would not be easier than just select field1,field2 ... field18 from blaBlaBla.
SELECT table_name=sysobjects.name,
column_name=syscolumns.name,
datatype=systypes.name,
length=syscolumns.length
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U'
and sysobjects.name='myTableName'
ORDER BY sysobjects.name,syscolumns.colid
will give you the list of your columns. You can write select generator based on this query.

I'd like to add to the answer of, "No, it's not possible directly in SQL". I would love to have that feature too! It sucks when you're trying to do some quick debugging on a 10+ column table that has a varbinary(max).
But I really just want to point out an alternative to Kane's tip for SSMS 2008 (Sql Server Management Studio).
If you open the Object Explorer (right-click in the query window and choose "Open Server in Object Explorer"), navigate to the node for the table in question. Expand the node so you can see the "Columns" node. Now "drag" the Columns node over to your query window and "drop" it. It will paste in all the column names for the table--and you can use it directly in a SELECT clause.

It is not possible as far as I know.

I have created a script for easy copy/pasting multiple columns, you might find it useful. See:
http://www.sqlservercentral.com/scripts/102375/
The script is explained in detail there, but in short for those who do not have an account on sqlservercentral:
It's a stored procedure that i can run using a shortcut. Type in your tablename (also works with temp tables and views), highlight it, hit the shortcut and it will display the columns of the table. From there you can easily copy multiple columns (the columns are also shown with a comma in front of the column name, so that also saves you some typing) and paste it in your query screen.
CREATE PROCEDURE [dbo].[sp_ColumnSelect]
#FullObjectName varchar(200)
AS
/*
Author: Robin van Schaik
Version: 1.3 (03-OCT-2012)
*/
DECLARE #Object varchar(200)
DECLARE #Schema varchar(200)
DECLARE #Database varchar(200)
DECLARE #IsTempTable bit
-- Break down parameter in Database/Schema/Object
SET #Object = PARSENAME(#FullObjectName,1)
SET #Schema = ISNULL(PARSENAME(#FullObjectName,2),'dbo')
SET #IsTempTable = case when left(#Object,1)='#' then 1 else 0 end
SET #Database = case when #IsTempTable=1 then 'tempdb' else PARSENAME(#FullObjectName,3) end
EXEC(
'SELECT
b.Name as ColumnStart
, '',''+b.Name as ColumnNext
, ''[''+b.Name+'']'' as ColumnStartBr
, '',[''+b.Name+'']'' as ColumnNextBr
FROM
' +#Database+'.sys.objects a
INNER JOIN
' +#Database+'.sys.columns b
ON a.object_id=b.object_id
INNER JOIN
' +#Database+'.sys.schemas d
ON a.schema_id=d.schema_id
WHERE
a.Object_ID=OBJECT_ID('''+#Database+'.'+#Schema+'.'+#Object+''')
AND d.name = '''+#Schema+'''
'
)

Related

Find out all useful columns in a table in sql server

I have a table which has 50+ columns but only few columns are getting used. that means when any stored procedure uses that table it only refers 4-5 columns in select/where statements . rest of columns are not getting used . i just want to list down those columns that are actually getting used. one way is finding out the dependencies of a table and then go through every SP and find out which columns are getting used . but in that case i have around 30+ Sp. is there any efficient way to do it.
To use multiple columns in a procedure, you can use a code like below
create procedure sp_sample
#column_names varchar(200)
as
if #column_names='' or #column_nams is null
set #column_names='*'
exec ('select '+#column_name +' from table')
Here are some examples :
exec sp_sample #columnname='id,name'
or
exec sp_sample #columnname='id,name,telphone'
Try this:
select name from syscomments c
join sysobjects o on c.id = o.id
where TEXT like '%table_name%' and TEXT like '%column_name%'
In table_name give you table name, in column_name give the column for which you want to chck the procedure dependencies.You will get the stored procedure names as output
If you import your database as a database project using the SQL Server Data Tools, you will be able to find all references to a table or column using the "Find All References" context command. What makes this particularly useful is the accuracy: it will even find instances of SELECT * that don't mention the column explicitly, but implicitly refer to it anyway. It will also not be confused by tables or columns with similar names (finding particular instances of ID is otherwise rather problematic).
If all you want to know if a column is referenced at all, you can simply delete it and see if any "unresolved reference" errors appear in the error list -- if yes, then the column is used somewhere.

SQL using REPLACE on one of many columns

I have the following query:
SELECT * FROM MailingList
There are about 20+ columns in the MailingList table, one which is called Address. This column has some fields which contain commas, which I need to take out. So I updated my query to:
SELECT REPLACE(Address, ',', '') AS Address, * FROM MailingList
But now I have two Address columns. Is there a way to only display one Address column while still using the wildcard (*) for all the other columns?
There is not a way to do this, though listing the columns you want explicitly is a good idea anyway.
You can trick as following query:
Get the data into a temp table
Drop the cloumns that are not needed
Get results and drop temp table
SELECT *, REPLACE(Address, ',', '') AS Address2
INTO #TempTable
FROM MailingList
ALTER TABLE #TempTable
DROP COLUMN [Address]
SELECT * FROM #TempTable
DROP TABLE #TempTable
I agree with Shadow - avoid using the * wild card if you can...
I know listing out ALL of the columns in select statement for big tables is a pain so here is a quick short cut you may not be aware of: In SQL Server Management Studio, browse through the object explorer and find the table you want to select from (MailingList). Right-click it to view the context menu and choose "Script Table as" then "SELECT TO" then "New Query Editor Window". This will create a new select statement with each column spelled out. In the future, use this method to create select statements, queries, procedures, etc. rather then the * wildcard. Performance is better and it just looks nicer :-)
Then you can solve your alias issue with the replace function.

No IntelliSense in SSMS 2008 for Table Valued Function

I'm building a Table Valued Function in SSMS, and I'm expecting IntelliSense to help me select columns, but it doesn't. Consider this:
CREATE FUNCTION dbo.My_TVF
(
)
RETURNS TABLE
AS
RETURN
(
SELECT [PO].I -- Here I is my cursor, ctrl+space does nothing
FROM dbo.SomePurchaseOrderView PO
JOIN dbo.SomePurchaseOrderLineView POL ON PO.PO_NUM = POL.PO_NUM
WHERE PO.PO_NUM IN (
SELECT TOP 500 PO_NUM
FROM dbo.SomeTable
WHERE PROCESSED = 0
)
)
GO
I want it to suggest column names for the select clause.
Notes:
The cache is fresh (CTRL + SHIFT + R)
IntelliSense works fine in general, this is the only situation I've encountered where it doesn't.
I'm querying a view instead of a table, if it matters.
I know it often fails when there is some kind of syntax error in what you are writing, but I can execute my query just fine when I specify a column.
On msdn it says: "IntelliSense is available for the SELECT statement when it is coded by itself, but not when the SELECT is contained in a CREATE FUNCTION statement."
Although, when testing it in my SSMS 2012, it does seem to work...
Source: http://msdn.microsoft.com/en-us/library/bb934481.aspx
(sorry, I don't have enough rep for a comment...)
I have found a blog posted by Pinal Dave on SQL Server Authority related intellisense.
Here's the link:
http://blog.sqlauthority.com/2009/03/31/sql-server-2008-intellisense-does-not-work-enable-intellisense/
Follow the below steps from the blog:
1) Make sure you are connected to SQL Server 2008 Edition.
2) IntelliSense should be enabled.
a) From Toolbar
b) Go to Tools >> Options >> Text Editor >> Transact-SQL >> IntelliSense
3) IntelliSense should be refreshed with the latest changes in database.
a) Press CTRL+SHIFT+R
b) Go to Edit >> IntelliSense >> Refresh Local Cache
4) Go to Tools >> Options >> Text Editor >> Transact-SQL >> General >> IntelliSense
Here are few assumptions:
You are connected to the right SQL Server that has the tables listed in query below.
You are not using index hints. I have had problems with intellisense and index hints.
I was able to reproduce the problem on my computer, looks like you need to type a comma before SSMS will suggest the next column.
CREATE FUNCTION dbo.My_TVF
(
)
RETURNS TABLE
AS
RETURN
(
SELECT [PO].I X -- If you press ctrl+space at the location of X it does nothing
-- since it has already suggested that column, PO.I (that's my assumption)
-- for next columns type a comma after PO.I and press ctrl+space.
-- I had no problems getting suggestions for other columns.
FROM dbo.SomePurchaseOrderVIEW PO
JOIN dbo.SomePurchaseOrderLineView POL ON PO.PO_NUM = POL.PO_NUM
WHERE PO.PO_NUM IN (
SELECT TOP 500 PO_NUM
FROM dbo.SomeTable
WHERE PROCESSED = 0
)
)
GO

Create an insert script from select results

Using SQL Server Management Studio is there a way I can select one or more rows in the grid of select results and have SQL Server Mangement Studio generate one or more insert statements (one for each row selected) which would insert that data into a table with the same schema?
Edit: I know how to create one manually, but I was hoping there would be something that would create it automatically for me. If you are familiar with Toad there is a way to have Toad generate inserts based on data in the results pane and I was hoping SSMS had an equivalant function.
Try to save the query result into a disposable table.
For example:
SELECT * INTO disposable_customer_table FROM customer_table WHERE id IN (in range of something)
Then do a db -> Tasks -> Generate Scripts.
Select specific database objects.
Choose disposable_customer_table from the list of table names.
Choose Save to file.
Make sure to do an Advance setup and select "Data only" from the 'Types of data to script'.
Tweak the result file and rename the disposable_customer_table back to the original table name.
Clean it up and drop the disposable_customer_table.
select 'insert into tableB values (', tableA.x ,',',tableA.y,',',tableA.z,')' from tableA
I think you have two options here:
Create your inserts manually. For instance:
select Name, Surname,
'insert into Person (Name,surname) values ('''+Name+''','''+Surname+')'
from Person
This gets you the results and, in the last column, the insert script for the row. You can then select and paste it in an Editor window.
Right click on the db -> Tasks -> Generate Scripts. Press then Advance and select "Data Only" (Default is Schema Only).
Perform your query and right click on the blank area where the column headers meet the row number in the Results view.
You can then select Script Grid Results:

T-SQL, Cursors, FETCH INTO. How to use SELECT *

I am building a one off query to iterate through a set of joined tables. The select statement is using "SELECT *". Since it's is a table with lots of fields, I don't want to specify each column as a variable. Is there a way to FETCH INTO an array or SET of some sort and just grab the values I want?
Apparently not:
INTO #variable_name[ ,...n]
"Allows data from the columns of a fetch to be placed into local variables.
Each variable in the list, from left to right, is associated with the corresponding column in the cursor result set. The data type of each variable must either match or be a supported implicit conversion of the data type of the corresponding result set column. The number of variables must match the number of columns in the cursor select list."
If you are looking to use cursors you may find better flexibility with CLR Stored procedures
Even if there was, you wouldn't want to. Fetching extra fields is one of the most common causes of performance degredation in a SQL Server application. By doing so, you restrict the optimizer's ability to use indexes effectively.
How would you propose to "grab the values that you want" without specifying column names?
Why do you need to use a cursor? Those are frowned upon in SQL Server scenarios - most of the time, they're unnecessary, and usually they're very slow and hurt performance.
What are you trying to accomplish with your cursor? Couldn't you do it in a set-based manner and use SQL Server's abilities to the max??
Marc
In 2k5 (SQL 2000 has different system objects), use the SQL metadata to quickly write queries with long lists of table/column names:
SELECT
O.Name + '__' + C.Name + ' = ' + O.Name + '.' + C.Name + ','
FROM Sys.Objects O
JOIN Sys.Columns C
ON C.Object_Id = O.Object_Id
WHERE O.Name IN ('Table1', 'Table1')
ORDER BY O.Name, C.Column_Id
I'm not sure exactly what you're trying to do with the result set, but this might be a decent start.
Also, you could declare variables as SQL_VARIANT and FETCH result sets into them like this:
DECLARE #Col1 SQL_VARIANT
SELECT #Col1 = Table1.Column1 FROM Table1
PRINT CONVERT(varchar(max), #Col1)
I'm not sure what that gains you though.
This is being suggested only for those that work with SQL daily, not specifically to answer this question.
The RedGate product SQL Prompt has the ability to expand wild-card characters into individual field names by using short-cut keys (Ctrl-B, Ctrl-W). This can save you alot of time and make it easier to remove a few fields from the query for those occasions where you do need most of them.
In SQL2005 you could also right-click the table an choose open table. Then you click the little SQL-Icon and you see the select statement, something like select * from YourTable. Clicking again on the !-icon the select * from will be expanded to the full fieldlist.
Good luck.