Selecting COUNT(*) with DISTINCT

Count all the DISTINCT program names by program type and push number SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] FROM cm_production WHERE push_number=@push_number GROUP BY program_type DISTINCT COUNT(*) will return a row for each unique count. What you want is COUNT(DISTINCT <expression>): evaluates expression for each row in a group and returns the number … Read more

Insert multiple rows WITHOUT repeating the “INSERT INTO …” part of the statement?

Your syntax almost works in SQL Server 2008 (but not in SQL Server 20051): CREATE TABLE MyTable (id int, name char(10)); INSERT INTO MyTable (id, name) VALUES (1, ‘Bob’), (2, ‘Peter’), (3, ‘Joe’); SELECT * FROM MyTable; id | name —+——— 1 | Bob 2 | Peter 3 | Joe 1 When the question was … Read more

Check if a temporary table exists and delete if it exists before creating a temporary table

I cannot reproduce the error. Perhaps I’m not understanding the problem. The following works fine for me in SQL Server 2005, with the extra “foo” column appearing in the second select result: IF OBJECT_ID(‘tempdb..#Results’) IS NOT NULL DROP TABLE #Results GO CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT ) GO select company, … Read more

SQL update query using joins

UPDATE im SET mf_item_number = gm.SKU –etc FROM item_master im JOIN group_master gm ON im.sku = gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID = mm.ManufacturerID WHERE im.mf_item_number like ‘STA%’ AND gm.manufacturerID = 34 To make it clear… The UPDATE clause can refer to an table alias specified in the FROM clause. So im in this case … Read more

Check if table exists in SQL Server

For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version. To check if a table exists use: IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ‘TheSchema’ AND TABLE_NAME = ‘TheTable’)) BEGIN –Do Stuff END

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)