nvarchar(max) still being truncated

The problem is with implicit conversion. If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to nVarChar(4000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter! When concatenating long strings … Read more

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I’ve modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply). select ‘create table [‘ + so.name + ‘] (‘ + o.list + ‘)’ + CASE WHEN tc.Constraint_Name IS NULL THEN ” ELSE ‘ALTER … Read more

Why do I get “Procedure expects parameter ‘@statement’ of type ‘ntext/nchar/nvarchar’.” when I try to use sp_executesql?

Sounds like you’re calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR. e.g. This will give the error because @SQL needs to be NVARCHAR DECLARE @SQL VARCHAR(100) SET @SQL = ‘SELECT TOP 1 * FROM sys.tables’ EXECUTE sp_executesql @SQL So: DECLARE @SQL NVARCHAR(100) SET @SQL = ‘SELECT TOP 1 * FROM sys.tables’ … Read more

Declare Variable for a Query String

It’s possible, but it requires using dynamic SQL. I recommend reading The curse and blessings of dynamic SQL before continuing… DECLARE @theDate varchar(60) SET @theDate=””‘2010-01-01” AND ”2010-08-31 23:59:59”’ DECLARE @SQL VARCHAR(MAX) SET @SQL = ‘SELECT AdministratorCode, SUM(Total) as theTotal, SUM(WOD.Quantity) as theQty, AVG(Total) as avgTotal, (SELECT SUM(tblWOD.Amount) FROM tblWOD JOIN tblWO on tblWOD.OrderID = tblWO.ID … Read more

Table name as a PostgreSQL function parameter

Before you go there: for only few, known tables names, it’s typically simpler to avoid dynamic SQL and spell out the few code variants in separate functions or in a CASE construct. That said, what you are trying to achieve can be simplified and improved: CREATE OR REPLACE FUNCTION some_f(_tbl regclass, OUT result integer) LANGUAGE … Read more

Create PostgreSQL ROLE (user) if it doesn’t exist

Simple script (question asked) Building on @a_horse_with_no_name’s answer and improved with @Gregory’s comment: DO $do$ BEGIN IF EXISTS ( SELECT FROM pg_catalog.pg_roles WHERE rolname=”my_user”) THEN RAISE NOTICE ‘Role “my_user” already exists. Skipping.’; ELSE CREATE ROLE my_user LOGIN PASSWORD ‘my_password’; END IF; END $do$; Unlike, for instance, with CREATE TABLE there is no IF NOT EXISTS … Read more

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