Showing posts with label t-sql. Show all posts
Showing posts with label t-sql. Show all posts

Wednesday, September 14, 2016

Concatenating the same column from different rows in a sql query

SELECT DISTINCT a.Author,
 Books = STUFF(( SELECT ', ' + BookTitle
   FROM Books as b
   WHERE b.Author=a.Author 
   ORDER BY BookTitle
   FOR XML PATH('')
   ), 1, 1, '')
FROM Books as a
INNER JOIN (
 SELECT Author, COUNT(BookTitle) as BookCount
 FROM Books
 WHERE NOT Author IS NULL
 GROUP BY Author
 HAVING COUNT(BookTitle) > 5) as c ON a.Author=c.Author

Wednesday, July 22, 2015

How to rename and/or modify table column in SQL Server

Column rename is done using sp_rename stored procedure:
sp_RENAME '<tableName>.<oldColumnName>' , '<newColumnName>', 'COLUMN'

And column data type and/or nullability is modified the following way:
ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL];

Monday, December 10, 2012

How to modify a column data type in a table that is populated with data

1) Create a table with the same name _tem (example: Table1_tmp) with the correct structure

2) Load data from Table1 into Table1_tmp using INSERT INTO ... SELECT FROM

3) Drop Table1

4) Re-create Table1, using CREATE TABLE Table1 AS (SELECT * FROM Table1_tmp)

5) Drop Table1_tmp

Friday, September 28, 2012

SQL to get the names of the tables referenced in stored procedures

below is a simple sql to retrieve a list of all the stored procedures and the tables referenced in those procedures:

SELECT DISTINCT a.name AS [Procedure Name], b.name AS [Table Name]
FROM sysobjects as a
INNER JOIN sysdepends d ON a.id=d.id
INNER JOIN sysobjects b ON d.depid=b.id
WHERE a.xtype = 'P'
ORDER BY a.name, b.name